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);
October 31st, 2008 at 4:50 am
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.