Simple script to combine elements within nested list (A list’s elements are lists)

static void Main(string[] args) {   // initialize a list object with List<string> elements   List<List<string>> nestedList = new List<List<string>>();   // add an element to the main list object   nestedList.Add(new List() { "a", "b", "c" });   // add another element to the main list object    nestedList.Add(new List() { "d", "e", "f" });   // LINQ query to collect all the string elements from each   // element within the main list.   // ( see equivalent foreach loop below )   List<string> all = ( from n in nestedList                 from l in n select l).ToList();   // print it out   all.ForEach(new Action(delegate(string s) { Console.WriteLine(s); }));   // output: abcdef   Console.ReadLine(); }

The foreach loop way to combine all the elements.

// this is the traditional foreach loop for the LINQ // query above. foreach( List<string> n  in nestedList )     foreach( string l in n )         all.Add(l);

Tags: ,

One Response to “LINQ: Combine elements in nested collection”

  1. Thanks for this clear sample for nested collections. Found you via Google on top spot for “linq+nested+collection” and answered my query straight away.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>