andy
andy

Reputation: 485

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

Upvotes: 1

Views: 7345

Answers (2)

Orange Apartments
Orange Apartments

Reputation: 31

You can filter in this easier way

ViewBag.RoomList = new SelectList(db.rooms.Where(p => p.hotel_id == 626191), "room_id", "title");

Upvotes: 0

Corey Adler
Corey Adler

Reputation: 16137

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,
                                         });

Upvotes: 6

Related Questions