tags:

views:

54

answers:

2

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? :-)

+8  A: 

Try this:

parents.SelectMany(p => p.Children).ToArray()
schoetbi
Bingo Bango, SelectMany is one of the handi-dandiest parts of linq.
Jimmy Hoffa
He wants a List though. You'll need to have a List.AddRange(parents.SelectMany...)
Joel Etherton
@Joel Etherton: or just .ToList() instead of .ToArray() :)
Jimmy Hoffa
+1  A: 

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)

Peter Leppert