Question

Assuming one has the object IEnumerable<IEnumerable<T>>, what is the most concise way to get a list of distinct T from this object?

Sample code:

var listOfLists = new List<List<string>>();

listOfLists.Add(new string[] {"a", "b", "c", "c"}.ToList());
listOfLists.Add(new string[] {"a", "f", "g", "h"}.ToList());
listOfLists.Add(new string[] {"j", "k", "l"}.ToList());

List<string> distinctList = listOfLists.MagicCombinationOfEnumerableMethods();

Console.WriteLine(string.Join(", ", distinctList));

Output would be something like:

a, b, c, f, g, h, j, k, l
Was it helpful?

Solution

You need Enumerable.SelectMany

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence

List<string> distinctList = listOfLists.SelectMany(r => r).Distinct().ToList();

You can also modify your code for adding elements in list like:

listOfLists.Add(new List<string> {"a", "b", "c", "c"});

instead of creating an array and then converting it to list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top