LINQ: Combine elements in nested collection

By admin - Last updated: Thursday, February 14, 2008 - Save & Share - 5 Comments

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();
}

UPDATE:
Simply use

var all = nestedList.SelectMany();

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);



Posted in LINQ • Tags: , Top Of Page

5 Responses to “LINQ: Combine elements in nested collection”

Comment from Andy
Time October 31, 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.

Comment from Joshua
Time September 5, 2009 at 8:41 am

Awesome! This is just what I was looking for. I originally had the nested foreach’s that you also listed.

I think it’s more elegant to have

List neededCourses =
(from courseObject in students.Select(stu => stu.Value.Courses)
from individualCRN in courseObject
select individualCRN).Distinct().OrderBy(crn => crn).ToList();

than to have

var allCourses = students.Select(x => x.Value.Courses);
List neededCourses = new List();
foreach (var crse in allCourses)
{
foreach (int crn in crse)
neededCourses.Add(crn);
}
neededCourses = neededCourses.Distinct().OrderBy(x => x).ToList();

So I just wanted to say thanks!

Comment from Nick Olsen
Time July 15, 2010 at 4:14 am

Perfect. Exactly what I needed. Thanks!

Comment from El Guaparian
Time December 4, 2010 at 9:31 am

You need to look up how to use SelectMany(). That is all.

Comment from Ray
Time December 7, 2010 at 8:45 pm

@EL Guanparian,

True you are right. SelectMany does the job.
The post was written in rather early days.

Write a comment


Captcha: four + 8 =