Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Thanks.. hope the question was understanble

like image 811
LocustHorde Avatar asked Sep 09 '11 15:09

LocustHorde


People also ask

What is difference between select and SelectMany in LINQ?

Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.

What does LINQ Select Return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

What is SelectMany in LINQ C#?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.


2 Answers

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(); 
like image 153
Justin Niessner Avatar answered Sep 22 '22 02:09

Justin Niessner


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.

like image 28
Jim Wooley Avatar answered Sep 23 '22 02:09

Jim Wooley