Simplest way to form a union of two lists

前端 未结 5 1393
再見小時候
再見小時候 2020-12-08 03:56

What is the easiest way to compare the elements of two lists say A and B with one another, and add the elements which are present in B to A only if they are not present in A

相关标签:
5条回答
  • 2020-12-08 04:08

    If it is a list, you can also use AddRange method.

    var listB = new List<int>{3, 4, 5};  
    var listA = new List<int>{1, 2, 3, 4, 5};
    
    listA.AddRange(listB); // listA now has elements of listB also.
    

    If you need new list (and exclude the duplicate), you can use Union

      var listB = new List<int>{3, 4, 5};  
      var listA = new List<int>{1, 2, 3, 4, 5};
      var listFinal = listA.Union(listB);
    

    If you need new list (and include the duplicate), you can use Concat

      var listB = new List<int>{3, 4, 5};  
      var listA = new List<int>{1, 2, 3, 4, 5};
      var listFinal = listA.Concat(listB);
    

    If you need common items, you can use Intersect.

    var listB = new List<int>{3, 4, 5};  
    var listA = new List<int>{1, 2, 3, 4};  
    var listFinal = listA.Intersect(listB); //3,4
    
    0 讨论(0)
  • 2020-12-08 04:10

    The easiest way is to use LINQ's Union method:

    var aUb = A.Union(B).ToList();
    
    0 讨论(0)
  • 2020-12-08 04:17

    Using LINQ's Union

    Enumerable.Union(ListA,ListB);
    

    or

    ListA.Union(ListB);
    
    0 讨论(0)
  • 2020-12-08 04:23

    If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

    IEnumerable<int> first = new List<int>{1,1,2,3,5};
    IEnumerable<int> second = new List<int>{8,13,21,34,55};
    
    var allItems = first.Concat(second);
    // 1,1,2,3,5,8,13,21,34,55
    
    0 讨论(0)
  • 2020-12-08 04:29

    I think this is all you really need to do:

    var listB = new List<int>{3, 4, 5};
    var listA = new List<int>{1, 2, 3, 4, 5};
    
    var listMerged = listA.Union(listB);
    
    0 讨论(0)
提交回复
热议问题