Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

.net - Trying to get distinct values from two List<int> objects

I have 2 List objects:

List<int> lst1 = new List<int>();
List<int> lst2 = new List<int>();

Let's say they have values:

lst1.Add(1);
lst1.Add(2);
lst1.Add(3);
lst1.Add(4);

lst2.Add(1);
lst2.Add(4);

I need to get an object containing the "distinct" list of both of these; so in this case the return would be List {2, 3}.

Is there an easy way to do this? Or do I need to iterate through each value of the lists and compare?

I am open to using ObjectQuery, LINQ, etc as these lists are coming from a database, and could potentially be several hundred to several thousand entries long.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...