mxmissile
mxmissile

Reputation: 11673

Retrieve All Children From Parent[]

Given this class:

public class Parent
{
  public Child[] Children {get;set;}
}

And this array:

Parent[] parents;

How can I retrieve all the children from the parents array using Linq or something else? This seems bad:

IList<Child> children = new List<Child>();
foreach(var parent in parents)
  children.AddRange(parent.Children);

Or is that not so bad? :-)

Upvotes: 1

Views: 299

Answers (2)

PeterL
PeterL

Reputation: 1397

I don't think the solution you propose in the question is bad. It is very readable and easy to understand what is going on. Unless you have some reason you need to optimize this, I don't see any fault with it.

If you just really want to use Linq, that's another story (and in my opinion perfectly valid -- the more experience/practice with Linq, the better)

Upvotes: 1

schoetbi
schoetbi

Reputation: 12856

Try this:

parents.SelectMany(p => p.Children).ToArray()

Upvotes: 9

Related Questions