1

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

mxmissile
  • 11,464
  • 3
  • 53
  • 79

2 Answers2

9

Try this:

parents.SelectMany(p => p.Children).ToArray()
schoetbi
  • 12,009
  • 10
  • 54
  • 72
  • Bingo Bango, SelectMany is one of the handi-dandiest parts of linq. – Jimmy Hoffa Aug 06 '10 at 19:26
  • He wants a List though. You'll need to have a List.AddRange(parents.SelectMany...) – Joel Etherton Aug 06 '10 at 19:29
  • 1
    @Joel Etherton: or just .ToList() instead of .ToArray() :) – Jimmy Hoffa Aug 06 '10 at 19:29
  • @JimmyHoffa: ToList is way more time consuming, thats why I prefere ToArray – schoetbi Dec 23 '11 at 09:00
  • 1
    @JimmyHoffa: I just want to revert what I have said. I learned it better and i like to share this. See here http://stackoverflow.com/questions/1105990/is-it-better-to-call-tolist-or-toarray-in-linq-queries So it's better to profile things before assuming a situation. – schoetbi Jul 30 '13 at 19:45
1

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)

PeterL
  • 1,397
  • 11
  • 15