Lambda Query On Nested List Object

Viewed 322

I've a data structure of something like this:

class A
{
    List<B> data;
}

class B
{
    C data;
}

class C
{
    List<E> data;
}

class E
{
    int Id;
    string Name;
}

function GetEById(int id, List<A> data)
{
}

Now I need to build a Linq Lambda Expression where Id = something. I don't want to go for nested loops.

Any help will be greatfull.

1 Answers

Assuming your classes look like this:

public class A
{
    public List<B> Data { get; set; }
}

public class B
{
    public C Data { get; set; }
}

public class C
{
    public List<E> Data { get; set; }
}

public class E
{
    public int Id { get; set; }
    public string Name { get; set; }
}

You can create a method GetEById that uses Enumerable.SelectMany() to flatten the results and pick the first E object that matches the id with Enumerable.FirstOrDefault():

private static E GetEById(int id, IEnumerable<A> data)
{
    return data
        ?.SelectMany(a => a?.Data?.SelectMany(b => b?.Data?.Data))
        .FirstOrDefault(e => e?.Id == id);
}

Or you could collect all E objects into a IEnumerable<E> filtering with Enumerable.Where():

private static IEnumerable<E> GetAllEById(int id, IEnumerable<A> data)
{
    return data
        ?.SelectMany(a => a?.Data?.SelectMany(b => b?.Data?.Data))
        .Where(e => e?.Id == id);
}

You can try this on https://dotnetfiddle.net/

Note: You could also look into Null-conditional operators to ensure child properties don't execute if the parent property is null.

I would also name your class types better. Names such as A, B, C etc. don't really mean much, and makes it hard for the reader to understand what these classes do and represent.

Related