Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ 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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading