perene
perene

Reputation: 421

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. That is, if the RoomId is already given for another Hotel I don't want to add the Hotel again. I have tried lots of solutions and tried MoreLinq, but all I can find is how to get a distinct inner-list.

Upvotes: 1

Views: 2534

Answers (1)

Gilad Green
Gilad Green

Reputation: 37281

From what I understand you want to have a distinct list of RoomIds and for each one one Hotel:

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

Upvotes: 2

Related Questions