从数据库中过滤 MVC SelectList

Filtering an MVC SelectList from DB

如何过滤从数据库中填充的 Select列表?在这个例子中,我只希望白色兔子(颜色是兔子对象的属性)出现在列表中。我试图在 Select 的末尾添加一个位置,但我只能看到 Id 和 Name 作为我可以过滤的条件。

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

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

我以为我可以做这样的事情:

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

与 SQL 不同,在 LINQ 中,Where 子句往往出现在 之前 Select 子句(除非您只想过滤在您在 Select 子句中预测的那些字段上):

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

您可以用这种更简单的方式进行筛选

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