2

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.

2
  • Welcome @Ahmad Bukhari to Stack Overflow, It's usually a good idea to have a sample data with the corresponding result. Commented Mar 8, 2020 at 0:53
  • It does not seem simple but this might help stackoverflow.com/questions/50973631/… Commented Mar 8, 2020 at 1:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

FYI you don't need the null-conditional operator ?. after SelectMany as that will never return null.
Thank you. This is exactly what I needed. I was never comfortable with selectmany because I never looked into it But now after your answer I did and It make sense and seems very useful. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.