LINQ在嵌套列表 - 选择所有标识的 [英] Linq on a nested List - select all Id's

查看:115
本文介绍了LINQ在嵌套列表 - 选择所有标识的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的列表中,这样的事情:

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.

从酒店名单现在,我只想选择所有的 RoomId ..我困在这里,而试图巢所有名单。

Now from Hotels list, I just want to select all RoomId's.. I am stuck here, while trying to nest all list..

现在,我想这样的:

//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. 

我如何做到这一点吗?

访问所有项目的所有ID在嵌套列表..偶尔它抱怨的不能转换int值布尔值,我不知道这意味着什么...

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...

谢谢..希望问题是understanble

Thanks.. hope the question was understanble

推荐答案

当你上面贴真的层次没有多大意义,我(似乎RoomType和房间都向后),我会后一例如去用它:

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

这篇关于LINQ在嵌套列表 - 选择所有标识的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆