简体   繁体   English

Linq从嵌套列表中获取不同的列表

[英]Linq get distinct list from nested list

I have a object something like this 我有一个像这样的东西

List<Hotel> Hotels;

public class Hotel
{
  List<RoomType> RoomType;
}

public class RoomType
{
  Room Room;
}

public class Room
{
  int RoomId;
}

I want to end up with a list of Hotels but where the nested list of RoomType is distinct by the RoomId. 我想以酒店列表作为结尾,但其中RoomType的嵌套列表与RoomId不同。 That is, if the RoomId is already given for another Hotel I don't want to add the Hotel again. 也就是说,如果已经为另一个酒店提供了RoomId,则我不想再次添加酒店。 I have tried lots of solutions and tried MoreLinq, but all I can find is how to get a distinct inner-list. 我已经尝试了很多解决方案并尝试了MoreLinq,但是我能找到的就是如何获得与众不同的内部列表。

From what I understand you want to have a distinct list of RoomId s and for each one one Hotel : 据我了解,您希望拥有一个RoomId的清单,并且每个Hotel都有一个清单:

var result = hotels.SelectMany(hotel => hotel.RoomType.Select(room => new { Id = room.RoomId, Hotel = hotel }))
                   .GroupBy(item => item.Id)
                   .Select(group => group.FirstOrDefault());

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

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