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
Was it helpful?

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();

OTHER TIPS

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" });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top