mardi 15 avril 2014

.net - c#: Get-t distincte de IEnumerable < IEnumerable <T>> - Stack Overflow


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



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.



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


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.


Related Posts:

0 commentaires:

Enregistrer un commentaire