简体   繁体   English

嵌套列表上的Linq - 选择所有Id

[英]Linq on a nested List - select all Id's

I have a nested list, something like this: 我有一个嵌套列表,如下所示:

List<Hotel> Hotels;

public class Hotel
{
    List<RoomType> RoomType;
}

public class RoomType
{
    Room Room;
}

public class Room
{
    int RoomId;
}

It's a little convoluted, sorry couldn't think of a better mockup model. 这有点令人费解,抱歉想不出一个更好的模型模型。 The Idea is that I have many hotels, each hotels has many room types, and assume each room type has exactly one room object. 我的想法是,我有很多酒店,每个酒店都有很多房型,并假设每个房型都有一个房间对象。

Now from Hotels list, I just want to select all RoomId 's.. I am stuck here, while trying to nest all list.. 现在从酒店列表,我只想选择所有RoomId ..我被RoomId ,同时试图嵌套所有列表..

right now, I am trying this: 现在,我正在尝试这个:

//cant do this some invalid error
int[] AllRoomIds = Hotels.selectMany(x => x.Rooms)
                       .selectMany(y => y.RoomType.Room.Id).Distinct().ToArray()

//cant do this - z doesnt have anything
int[] AllRoomIds = Hotels.selectMany(x => x.Rooms)
                         .selectMany(y => y.RoomType)
                         .select(z => z. 

How do I do this please? 我该怎么办?

Accessing all id's of all items in a nested list.. occasionally it complains of cannot convert int to boolean and I do not know what it means... 访问嵌套列表中所有项目的所有id ..偶尔它会抱怨cannot convert int to boolean ,我不知道这意味着什么......

Thanks.. hope the question was understanble 谢谢..希望这个问题是可以理解的

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: 虽然您在上面发布的层次结构对我来说真的没有多大意义(似乎RoomType和Room是倒退的),但我会发布一个示例来配合它:

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. 听起来你需要选择RoomType.Room.Id而不是SelectMany。 Using the Query syntax (which I typically prefer over lambda syntax for SelectMany, it would be 使用Query语法(我通常更喜欢SelectMany的lambda语法,它会是

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. 这里有Hotels和Roomtype之间的SelectMany,但不是类型和Room之间的SelectMany。

Here is another approach using GroupBy (without Distinct ): 这是另一种使用GroupBy (没有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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM