Flatten a list of lists in C#
This post will discuss how to flatten a list of lists in C#.
1. Using Enumerable.SelectMany() method (System.Linq)
We can use LINQ’s SelectMany() method to map each element of a list to an IEnumerable<T> and flattens the resulting sequences into a single list. The following code example demonstrates how to use the SelectMany to flatten a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<List<int>> listOfLists = new List<List<int>>() { new List<int>() { 1, 2, 3 }, new List<int>() { 4, 5 }, new List<int>() { 6, 7, 8, 9 } }; List<int> flattenedList = listOfLists.SelectMany(x => x).ToList(); Console.WriteLine(String.Join(",", flattenedList)); } } /* Output: 1,2,3,4,5,6,7,8,9 */ |
2. Using LINQ Query Expressions
The following code example shows how to use LINQ query expressions to flatten a list:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<List<int>> listOfLists = new List<List<int>>() { new List<int>() { 1, 2, 3 }, new List<int>() { 4, 5 }, new List<int>() { 6, 7, 8, 9 } }; List<int> flattenedList = (from list in listOfLists from item in list select item).ToList(); Console.WriteLine(String.Join(",", flattenedList)); } } /* Output: 1,2,3,4,5,6,7,8,9 */ |
That’s all about flattening a list of lists in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)