Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 489
sofigi7386 Avatar asked Nov 01 '25 03:11

sofigi7386


2 Answers

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));
like image 126
Tim Schmelter Avatar answered Nov 03 '25 18:11

Tim Schmelter


Your current code flattens the hierarchy to collection of Chair and selects only their ids.

With pure LINQ you can do via nesting SelectMany and using Append/Prepend:

var ids = floors
    .SelectMany(f => f.Rooms
        .SelectMany(r => r.Chairs
            .Select(ch => ch.Id) // select chairs ids
            .Append(r.Id)) // append "current" room id to it's collection of chair ids
        .Append(f.Id)) // append "current" floor id to it's collection of rooms and chairs ids
    .ToList();
like image 20
Guru Stron Avatar answered Nov 03 '25 18:11

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!