Convert List> into List in C#

后端 未结 3 627
醉梦人生
醉梦人生 2020-12-10 11:08

I have a List>. I would like to convert it into a List where each int is unique. I was wondering if anyone had a

相关标签:
3条回答
  • 2020-12-10 11:29
    List<int> result = listOfLists
      .SelectMany(list => list)
      .Distinct()
      .ToList();
    
    0 讨论(0)
  • 2020-12-10 11:32
    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();
    
    0 讨论(0)
  • 2020-12-10 11:38

    How about:

    HashSet<int> set = new HashSet<int>();
    foreach (List<int> list in listOfLists)
    {
        set.UnionWith(list);
    }
    return set.ToList();
    
    0 讨论(0)
提交回复
热议问题