I have a List<List<int>>
. I would like to convert it into a List<int>
where each int is unique. I was wondering if anyone had an elegant solution to this using LINQ.
I would like to be able to use the Union method but it creates a new List<> everytime. So I'd like to avoid doing something like this:
List<int> allInts = new List<int>();
foreach(List<int> list in listOfLists)
allInts = new List<int>(allInts.Union(list));
Any suggestions?
Thanks!
Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.
The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.
Select(x => x.i); foreach(int i in indexes) { peopleInfo[i]. age ... }
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();
But these days I would actually write it as
var result2 = l.SelectMany(i => i).Distinct();
List<int> result = listOfLists
.SelectMany(list => list)
.Distinct()
.ToList();
How about:
HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
set.UnionWith(list);
}
return set.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With