Search code examples
c#linqlinq-to-entities

LINQ Select IDs from multiple levels


I'd like to get one list of IDs from all nested entities.

Code:

// Entities
class Floor
{
    public int Id { get; set; }
    public ICollection<Room> Rooms { get; set; } = new List<Room>();
}

class Room
{
    public int Id { get; set; }
    public ICollection<Chair> Chairs { get; set; } = new List<Chair>();
}
class Chair
{
    public int Id { get; set; }
}

// Setup
var floor = new Floor() { Id = 1000 };
var room = new Room() { Id = 100 };
var chair = new Chair() { Id = 10 };

room.Chairs.Add(chair);
floor.Rooms.Add(room);

var floors = new List<Floor>() { floor };

// Select all IDs
var ids = floors.???

Expected result:

{ 10, 100, 1000 }

What I've tried. It selects IDs only from the deepest level, not all of them:

// Select all IDs
var ids = floors
    .SelectMany(f => f.Rooms)
    .SelectMany(r => r.Chairs)
    .Select(ch => ch.Id)
    .ToList();

Solution

  • SelectMany is what you need together with Append:

    var ids = floors
        .SelectMany(f => f.Rooms
            .SelectMany(r => r.Chairs
                .Select(c => c.Id).Append(r.Id)).Append(f.Id));