Reputation: 900
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
Upvotes: 1
Views: 1005
Reputation: 223277
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.
Upvotes: 10