Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<List<T>> into List<T> in C#

Tags:

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!

like image 247
user57230 Avatar asked Jan 20 '09 20:01

user57230


People also ask

How do I convert a list to a different list?

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.

What is list t>?

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.

How to access data from list in c#?

Select(x => x.i); foreach(int i in indexes) { peopleInfo[i]. age ... }


3 Answers

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

But these days I would actually write it as

var result2 = l.SelectMany(i => i).Distinct();
like image 163
flq Avatar answered Sep 27 '22 05:09

flq


List<int> result = listOfLists
  .SelectMany(list => list)
  .Distinct()
  .ToList();
like image 16
Amy B Avatar answered Sep 24 '22 05:09

Amy B


How about:

HashSet<int> set = new HashSet<int>();
foreach (List<int> list in listOfLists)
{
    set.UnionWith(list);
}
return set.ToList();
like image 10
Jon Skeet Avatar answered Sep 24 '22 05:09

Jon Skeet