How to merge a list of lists with same type of items to a single list of items?

C#LinqLambda

C# Problem Overview


The question is confusing, but it is much more clear as described in the following codes:

   List<List<T>> listOfList;
   // add three lists of List<T> to listOfList, for example
   /* listOfList = new {
        { 1, 2, 3}, // list 1 of 1, 3, and 3
        { 4, 5, 6}, // list 2
        { 7, 8, 9}  // list 3
        };
   */
   List<T> list = null;
   // how to merger all the items in listOfList to list?
   // { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
   // list = ???

Not sure if it possible by using C# LINQ or Lambda?

Essentially, how can I concatenate or "flatten" a list of lists?

C# Solutions


Solution 1 - C#

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Solution 2 - C#

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

Solution 3 - C#

Do you mean this?

var listOfList = new List<List<int>>() {
	new List<int>() { 1, 2 },
	new List<int>() { 3, 4 },
	new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

Solution 4 - C#

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid.Chu.caView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Joe ChungView Answer on Stackoverflow
Solution 3 - C#IRBMeView Answer on Stackoverflow
Solution 4 - C#ArmanView Answer on Stackoverflow