How to compare 2 List objects to get the missing value from the List

前端 未结 5 676
走了就别回头了
走了就别回头了 2021-01-27 02:23

How do I use the \"NOT IN\" to get the missing data, to be added to \"foo\" List.

var accessories = new List(); 
var foo = new List()         


        
相关标签:
5条回答
  • 2021-01-27 02:41

    You can combine Concat and Distinct to do this:

    foo = foo.Concat(accessories).Distinct().ToList();
    

    Edit: Or Except as others have pointed out, which seems to be the superior choice for this case.

    0 讨论(0)
  • 2021-01-27 02:49

    If you just want foo to be the distinct combination of all elements in foo and accessories (i.e., the union of the two lists),

    List<string> foo = foo.Union(accessories).ToList();
    
    0 讨论(0)
  • 2021-01-27 02:50

    There's a LINQ method to do this for you, it looks like this; accessories.Except(foo);

    0 讨论(0)
  • 2021-01-27 02:52

    You can use .Except() to get the difference between two sets:

    var difference = accessories.Except(foo);
    // difference is now a collection containing elements in accessories that are not in foo
    

    If you then want to add those items to foo:

    foo = foo.Concat(difference).ToList();
    
    0 讨论(0)
  • 2021-01-27 02:58

    Use List.Except:

    foo.AddRange(accessories.Except(foo));
    

    From MSDN:

    Except Produces the set difference of two sequences.

    0 讨论(0)
提交回复
热议问题