Wednesday, December 23, 2009

Flatten array of arrays using linq

If you have list of object that contains list of other objects and you want to collect all children in one list linq can make it simple. For example:


List<int> listOfInt = new List<int>();
List<List<int>> listOfListOfInts = new List<List<int>>();
foreach (List<int> ints in listOfListOfInts)
{
foreach (int i in ints)
{
listOfInt.Add(i);
}
}


but using linq the following statements become:


List<int> listOfInt = listOfListOfInts.SelectMany(ints => ints).ToList();

1 comment:

Seba said...

Nice one. thanks very much for this post