【问题标题】:Filtering an MVC SelectList from DB从 DB 中过滤 MVC SelectList
【发布时间】:2015-01-07 19:52:31
【问题描述】:

如何过滤从数据库中填充的 SelectList?在这个例子中,我只希望白色兔子(颜色是兔子对象的属性)出现在列表中。我试图在 Select 的末尾添加一个 where 但我只能看到 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");

【问题讨论】:

    标签: c# asp.net-mvc linq linq-to-sql


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以用这种更简单的方式过滤

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        相关资源
        最近更新 更多