Konvertieren List > in List in C #
Frage
Ich habe eine List<List<int>>
. Ich möchte es in ein List<int>
umwandeln, wo jeder int einzigartig ist. Ich habe mich gefragt, ob jemand eine elegante Lösung für dieses mit LINQ hat.
Ich möchte in der Lage sein, um die Union-Methode zu verwenden, aber es schafft eine neue List <> jedes Mal. So würde Ich mag so etwas vermeiden tun:
List<int> allInts = new List<int>();
foreach(List<int> list in listOfLists)
allInts = new List<int>(allInts.Union(list));
Irgendwelche Vorschläge?
Danke!
Lösung
List<List<int>> l = new List<List<int>>();
l.Add(new List<int> { 1, 2, 3, 4, 5, 6});
l.Add(new List<int> { 4, 5, 6, 7, 8, 9 });
l.Add(new List<int> { 8, 9, 10, 11, 12, 13 });
var result = (from e in l
from e2 in e
select e2).Distinct();
Update 09.2013
Aber in diesen Tagen würde ich es eigentlich schreiben, wie
var result2 = l.SelectMany(i => i).Distinct();
Andere Tipps
List<int> result = listOfLists
.SelectMany(list => list)
.Distinct()
.ToList();
Wie wäre:
HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
set.UnionWith(list);
}
return set.ToList();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow