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<T>
instead of an IEnumerable<T>
.)
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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…