Mohan Kumar
Mohan Kumar

Reputation: 6056

iterating through the hierarchy of objects - C# - linq

I have an object (say A) with hierarchy as below,

obj A --> Contains list of obj B --> Contains list of obj C --> Contains list of obj D

Given the obj A, i need to get the list of all obj D in total, irrespective of its association with obj C and obj B. something like List<D> GetAllofD(A a)

Can you please suggest me the best way to get it done - don't want to use multiple for loops. Any better approach using linq?

Upvotes: 2

Views: 1059

Answers (2)

feiyun0112
feiyun0112

Reputation: 771

handle null condition for collections

a.b == null ? new List<D>() : a.b.SelectMany(b=>b.c==null ? new List<D>() : b.c.SelectMany(c=>c.d)) 

Upvotes: 1

StuartLC
StuartLC

Reputation: 107247

As per @feiyun's comment, repeated application of SelectMany can be used to progressively rollup all levels of the class hierarchy:

var allDsInTheTree = new A().Bs.SelectMany(b => b.Cs.SelectMany(c => c.Ds));

Given the class hierarchy:

public class D { public int Id { get; set; } }
public class C {
    public IEnumerable<D> Ds { get; set; }
}
public class B
{
    public IEnumerable<C> Cs { get; set; }
}
public class A
{
    public IEnumerable<B> Bs { get; set; }
}

SelectMany at a single level would be something similar to:

var cs = new List<C>();
foreach (var b in a.Bs)
{
   cs.AddRange(b.Cs);
}

Upvotes: 1

Related Questions