Set Attribute to ListItem in Linq Query - c#

From list i am populating ListItem for dropdown list.
var list = LoadList();
var listitems = list.Select(l => new ListItem
{
Value = l.Id,
Text = l.Description
Attributes ????
}).ToList();
On the Linq query I want to add attribute. Attributes.Add() method is not accessible. Any idea?

From MSDN, the Attributes property is read only:
[BrowsableAttribute(false)]
public AttributeCollection Attributes { get; }
so you will not be able to do it using the object initialisers.
You could do this by doing something like:
var listitems = list.Select(l => { var li = new ListItem
{
Value = l.Id,
Text = l.Description
}; li.Attributes.Add(....); return li; ).ToList();

Related

How can I create a list inside a list with a foreach in c# ?

In other words I need all the elements of list "Categories" to be the "Parent" and elements of list "commodities" be the children.
Example
public string GetCommodities()
{
List<dynamic> categories = new List<dynamic>();
List<dynamic> commodities = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
categories.Add(new
{
comcat.Category,
});
foreach (var com in comcat.Commodities.OrderBy(o => o.Name))
{
commodities.Add(new
{
com.Name,
});
}
}
var response = new JavaScriptSerializer().Serialize(commodities);
return response;
}
And see if it's possible to all commodities names inside each category, within this foreach.
I tried adding a dynamic list such as:
dynamic listOfElements = new { CAT = categories, COMM = commodities };
But it does't return elemnts as parents or dependency of categories. Is the same as adding
commodities.Add(new
{
comcat.Category,
com.Name,
});
public string GetCommodities()
{
List<dynamic> categoryCommodityList = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
var allCommodities = comcat.Commodities.OrderBy(o => o.Name).Select(com => com.Name).ToList();
categoryCommodityList.Add(new { Catagory = comcat.Category, Items = allCommodities } );
}
return new JavaScriptSerializer().Serialize(categoryCommodityList);
}
You class structure does not support parent-child relationships. I mean, if what you want is that each Category holds a list of commodities, then you would need something like this:
var result = from c in comcat
select new { Category = c, Commoddities = c.Commoddities};
This will return a hierarchy of Categories including all Commodities underneath it.
If you are just receiving a flat data set, then you need something like this:
var result = from c in comcat
select new { Category = c,
Commoddities = c.Where(x=>x.Category.Name == c.Name).Select(x=>x.Commodity) };
Hopefully you get the idea...

How to cast a List<T> object into Text

I want to know if I can access an item of my List and assign it to a textbox?
public static List<Product> detailsList = new List<Product>();
Product is my class generated by using LINQ to SQL with fields Name,Code,Details i.e my List contains the items(Name,Code,Details). I want to access the value of the item Details from the list and assign it to a textbox . Something like:
txtDetails.Text = detailsList.Details.ToString()
If you want the details of 1 item:
var detailsList = new List<TaskDto>();
// add items
// this if you know the corect index
txtDetails.Text = detailsList[0].Details;
// if you need to query for example for the item with the correct Id
txtDetails.Text = detailsList.FirstOrDefault(p => p.Id == 1).Details;
You can select first or default from the item based on some criteria, like the name.
public static List<Product> detailsList = new List<Product>();
var prod = detailsList.FirstOrDefault(p => p.Name == 'Ana');
if(prod != null) {
txtDetails.Text = prod.Details;
}
For all items:
var joinSymbol = ", ";
txtDetails.Text = string.Join(joinSymbol, detailsList.Select(detail => detail.Details));
For first item if Details:
txtDetails.Text = detailsList.FirstOrDefault()?.Details ?? string.Empty;
use string.Join() function.
txtDetails.Text = string.Join(",", detailsList.Select(e => e.Details)).ToList());

Using LINQ to build a cascading list in C#

I have a need to display a list of departments and sub-departments. I am loading the list of departments properly.
At this time, I have:
var deparmentList = Departments.LoadList();
var departments = new List<ListItem>(
from department in departmentList
select new ListItem {
Text = department.Name,
Value = department.Id.ToString(),
IsSelected = department.IsActive
}
);
I now need to load the list of sub-departments. Each sub-department has an Id, DepartmentId, and Name. However, I only want to get the sub-departments associated with departments that are selected. Currently, I have the following:
var subDepartmentList = SubDepartment.LoadList();
var subdepartments = new List<ListItem>(
from subdepartment in subDepartmentList
// where ?
select new ListItem {
Text = subdepartment.Name,
Value = subdepartment.Id.ToString(),
IsSelected = false
}
);
I'm not sure how to do the join or filter between the two. How do I do this in LINQ?
var selectedDepartmentSubDepartments =
from dep in departments
join subDep in subDepartmentList
on dep.Value equals subDep.Id.ToString()
where dep.IsSelected
select new ListItem {
Text = subDep.Name,
Value = subDep.Id.ToString(),
IsSelected = false
};
var subdepartments = new List<ListItem>(selectedDepartmentSubDepartments);
You can add a where clause that checks if at least one associated and 'selected' department exists:
var subDepartmentList = SubDepartment.LoadList();
var subdepartments = new List<ListItem>(
from subdepartment in subDepartmentList
where departments.Any(x => x.IsSelected &&
x.Value == subdepartment.DepartmentId.ToString())
select new ListItem {
Text = subdepartment.Name,
Value = subdepartment.Id.ToString(),
IsSelected = false
}
);

Saving values into List in a class by using LINQ

I have a class Item with a string List ImagesUrl property:
public class Item
{
string Name { get; set; }
List<string> ImagesUrl { get; set; }
..
}
And I want to parse a XML file and save each node item into var items. In node item there are nodes img1, .. , img5 and right these I want to save into the Img property by using LINQ command like this:
var items = from item in xmlDocument.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = item.Element("img1").Value, //....?
..
};
How you can see, I don't know how I could save the img1..5 values in LINQ. Could someone help me?
var items = from item in xmlDocument.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = Enumerable.Range(1,5).Select(x => item.Element("img"+x).Value).ToList();
};
Code is self-explanatory here.
Universal solution independent on count of imgX elements
var items = from item in Xml.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = item.Elements()
.Where(e => e.Name.LocalName.StartsWith("img"))
.Select(e => e.Value)
.ToList()
};

Object reference error adding a new select list item

I'm having a problem with the List<SelectListItem>. Whenever the code hits the foreach it says:
object reference not set to an instance of an object.
Am I missing something or can anyone explain why it is failing there?
public ActionResult HammerpointVideos(string category, string type)
{
var stuff = Request.QueryString["category"];
var ItemId = (from p in entities.EstimateItems
where p.ItemName == category
select p.EstimateItemId).FirstOrDefault();
var Videos = (from e in entities.EstimateVideos
where e.EstimateItemId == ItemId
select new Models.HammerpointVideoModel
{
VideoName = e.VideoName,
VideoLink = e.VideoLink
}).ToList();
var model= new Models.HammerpointVideoListModel();
List<SelectListItem> list = model.VideoList;
foreach (var video in Videos)
{
list.Add(new SelectListItem()
{
Selected=false,
Value = video.VideoLink,
Text = video.VideoName
});
}
}
Is ViedoList initialized before? I assume it is not. Create new list add items to it and after that add reference to it in your model:
var model = new Models.HammerpointVideoListModel();
List<SelectListItem> list = new List<SelectListItem>();
foreach (var video in Videos)
{
list.Add(new SelectListItem()
{
Selected=false,
Value = video.VideoLink,
Text = video.VideoName
});
}
model.VideoList = list;
Probably You didn't initialized VideoList in the parameterless constructor of HammerpointVideoListModel class, so it is NOT an empty list.
Put
VideoList = new List<SelectedListItem>();
in the constructor.

Categories

Resources