Trying to get distinct values from two List objects

后端 未结 6 852
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:24

    Ahmad is nearly right with Except, I believe - but that won't give you items which are in lst2 but not in lst1. So in the example you gave, if you added 5 to lst2, I imagine you'd want the result to be {2, 3, 5}. In that case, you want a symmetric difference. I don't think there's any way to do that directly in LINQ to Objects in a single call, but you can still achieve it. Here's a simple but inefficient way to do it:

    lst1.Union(lst2).Except(lst1.Intersect(lst2)).ToList();
    

    (Obviously you only need ToList() if you genuinely need a List instead of an IEnumerable.)

    The way to read this is "I want items that are in either list but not in both."

    It's possible that it would be more efficient to use Concat - which would still work as Except is a set based operator which will only return distinct results:

    lst1.Concat(lst2).Except(lst1.Intersect(lst2)).ToList();
    

提交回复
热议问题