andy andy - 1 month ago 19
C# Question

Filtering an MVC SelectList from DB

How would I filter a SelectList being populated from the database? In this example, I only want white bunnies (Color is the property on the bunnies object) to show up in the list. I have tried to add a where on the end of the Select but I only can see Id and Name as conditions I can filter on.

var bunnies = db.Bunnies.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name,

}
);
return new SelectList(bunnies , "Value", "Text");


I thought I could do something like this:

var bunnies = db.Bunnies.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name,

}
).Where(p => p.Color == "white");
return new SelectList(bunnies , "Value", "Text");

Answer

Unlike in SQL, in LINQ the Where clause tends to come before the Select clause (unless you want to filter only on those fields that you've projected out in the Select clause):

var bunnies = db.Bunnies.Where(p => p.Color == "white")
                        .Select(x => new SelectListItem
                                         {
                                            Value = x.Id.ToString(),
                                            Text = x.Name,
                                         });