Trying to get distinct values from two List objects

后端 未结 6 854
Happy的楠姐
Happy的楠姐 2020-12-18 00:47

I have 2 List objects:

List lst1 = new List();
List lst2 = new List();

Let\'s say they have val

6条回答
  •  既然无缘
    2020-12-18 01:23

    EDIT: thanks to the comments you need to do some extra work besides just using Except to get a symmetric difference. If an additional value is added to the 2nd list Except alone would be incorrect. To get the proper result try this:

    var list1 = new List(Enumerable.Range(1,4));
    var list2 = new List { 1, 4, 6 };
    
    var result = list1.Except(list2).Union(list2.Except(list1));
    

    The above returns {2, 3, 6}.

    Note that you'll need to add a ToList() if you really need a List, otherwise the above operation will return an IEnumerable.


    Use the Enumerable.Except method, which produces the set difference of two sequences:

    var result = lst1.Except(lst2);
    

提交回复
热议问题