Linq on a nested List - select all Id's

左心房为你撑大大i 提交于 2019-12-03 05:25:52

While the hierarchy you posted above really doesn't make much sense to me (seems RoomType and Room are backwards), I'll post an example to go with it:

Hotels.SelectMany(h => h.RoomType)
      .Select(rt => rt.Room.Id)
      .Distinct()
      .ToArray();

Sounds like you need a Select for the RoomType.Room.Id rather than SelectMany. Using the Query syntax (which I typically prefer over lambda syntax for SelectMany, it would be

var query = (from hotel in Hotels
            from type in Hotel.RoomType
            select type.Room.Id)
            .Distinct.ToArray();

Here you have a SelectMany between Hotels and Roomtype, but not one between type and Room.

Here is another approach using GroupBy (without Distinct):

int[] allRoomIds = Hotels.SelectMany(h => h.RoomType)
      .GroupBy(rt => rt.Room.Id)
      .Select(room => room.Room.Id)
      .ToArray();

If you will need the list of object:

List<Room> allRooms = Hotels.SelectMany(h => h.RoomType)
     .GroupBy(rt => rt.Room.Id)
     .Select(room => room.First())
     .ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!