代码之家  ›  专栏  ›  技术社区  ›  Bill

如何通过添加范围和选择条件组合到通用列表?

  •  0
  • Bill  · 技术社区  · 7 年前

    如何通过添加范围和选择条件组合到通用列表?这是一个虚构的例子。我可以添加范围,但不能根据房间类型等条件进行筛选。“select(mr=>mr.type==roomtype.bedroom)”不起作用。我可以用什么来代替在type=bedroom的地方添加列表呢?

    public enum RoomType
    {
        Bathroom = 1,
        BedRoom = 2,
        Kitchen = 3,
        RecRoom = 4
    }
    
    public class RoomsModel
    {
        public RoomType Type { get; set; }
        public int Size { get; set; }
    }
    
    public List<RoomsModel> GetRooms(params)
    {
        var result = new List<RoomsModel>();
    
        result = _service.GetRooms(house1);
    
        var moreRooms _service.GetRooms(house2);
    
        result.AddRange((from mr in moreRooms
                     select new RoomsModel
                     {
                         Type = mr.Type,
                         Size = mr.Size
                     }
                     ).Select(mr => mr.Type == RoomType.BedRoom).ToList());
    
        return result;
    }
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Josef Bláha N.Tesla    7 年前

    使用 Where 而不是 Select 以下内容:

    result.AddRange(
      from mr in moreRooms
      where mr.Type == RoomType.BedRoom
      select new RoomsModel
      {
        Type = mr.Type,
        Size = mr.Size
      });
    

    在哪里? 筛选项目。 选择 项目项,即将序列中的每个项转换为其他项。

        2
  •  1
  •   gabriel.hayes    7 年前

    你需要使用 Where 而不是 Select 以下内容:

    result.AddRange((from mr in moreRooms
                     select new RoomsModel
                     {
                         Type = mr.Type,
                         Size = mr.Size
                     }
                     ).Where(mr => mr.Type == RoomType.BedRoom).ToList());
    
    
        3
  •  0
  •   circa94    7 年前

    还有一种方法:

     result.AddRange(moreRooms.Where(mr => mr.Type == RoomType.BedRoom)
       .Select(mr => new RoomsModel {
         Type = mr.Type, 
         Size = mr.Size
       }));