LINQ (Language Integrated Query) is a powerful feature in C#. It simplifies a way to query database in the C#.
Recently, I came across the question raised by my team member on how to flatten the nested lists (List of lists) when querying the data in C#. So, I thought of go through the approach with an example using LINQ in this article.
Let’s try with the simple example of list of integers as below.
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 }
};
In the above example, it contains list of lists. If we want to merge this nested list in to a single list, we can use SelectMany()
in LINQ.
SelectMany() – Map each element of a list to an IEnumerable<T>
and flattens the resulting sequences into a list.
List<int> flattenedList = listOfLists.SelectMany(_ => _).ToList();
Console.WriteLine(String.Join(",", flattenedList));
/*
Output: 1,2,3,4,5,6,7,8,9
*/
The above code snippet will flatten the list of numeric list in to a single numeric list.
Lets take a look with a complex objects.
class Person
{
public string Name { get; set; }
public List<Person> Children { get; set; }
}
List<Person> parents = new List<Person>() {
new Person() {
Name = "parentA",
Children = new List<Person>() {
new Person() { Name = "childA1" },
new Person() { Name = "childA2" }
}
},
new Person() {
Name = "parentB",
Children = new List<Person>() {
new Person() { Name = "childB1" },
new Person() { Name = "childB2" }
}
}
};
var result = parents.SelectMany(person => person.Children)
.Select(p => p.Name);
result.Select(_ => Console.WriteLine(_));
/*
Output:
childA1
childA2
childB1
childB2
*/
I would strongly recommend to consider using selectMany()
to flatten nested lists into a single collection. Because, it’s ability to flatten and transform in to a collection in a single method call is efficient and reduce the need to chain together subsequent LINQ calls to transform the result collection.
Happy C’Sharping 🙂