LINQ query add extra value after select
-
06-05-2021 - |
Question
i am populating a "Category" dropdown list with LINQ. (Northwind databse)
var Category = (from cat in _db.Categories.ToList()
select new SelectListItem
{
Text = cat.CategoryName,
Value = cat.CategoryID.ToString()
}).ToList();
I wish to add an extra value at the beginning of this list to be the filter reset, something like "All" so i expect the dropdown to be something like :
- All //added
- Beverages // from query
- Condiments // from query
La solution
var Category = new[]{ new SelectListItem(){ Text = "All" } }.Concat(
from cat in _db.Categories.ToList()
select new SelectListItem
{
Text = cat.CategoryName,
Value = cat.CategoryID.ToString()
}).ToList();
Autres conseils
You can use Concat
with an array constant, like this:
var Category = new [] { new SelectListItem {Text="All"}}
.Concat(from cat in _db.Categories.ToList()
select new SelectListItem {
Text = cat.CategoryName
, Value = cat.CategoryID.ToString()
}
).ToList();
You can Insert a value into a list at the desired position. That should do the trick.
List<T>
has an Insert method:
Category.Insert(0, new SelectListItem { Text="All" });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow