Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lambda

linq

People also ask

How do I merge a list of lists into one list?

Join a List of Lists Into a List Using the Chain() Method. In the above program, the chain() method is used to iterate all the sub-lists in the list of lists and return a single iterable list containing all elements of all sub-lists.

How do you combine lists within a list Python?

📢 TLDR: Use + In almost all simple situations, using list1 + list2 is the way you want to concatenate lists. The edge cases below are better in some situations, but + is generally the best choice. All options covered work in Python 2.3, Python 2.7, and all versions of Python 31.

How do I concatenate a nested list in Python?

Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.


Use the SelectMany extension method

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

Here's the C# integrated syntax version:

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

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


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.