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.
📢 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With