Reputation: 16040
I am comparing 2 hashsets full of filenames.I have successfully implemented "ExceptWith" but now I need to get a list of "all filenames that are in both sets."
I know hashset has a contains but that means looping the hashset for each item of the other one. Wondering if there is an inbuilt method to do this. I am doing with files with over 50000 filenames.
many thanks
Upvotes: 0
Views: 162
Reputation: 164291
What you are talking about is a set intersection. There is a built in method for that:
HashSet<string> x = new HashSet<string> { "x", "a","b"};
HashSet<string> y = new HashSet<string> { "z", "a","b"};
x.IntersectWith(y);
Note that this modifies the original HashSet x
. If you don't want that, use the extension method on Enumerable:
var intersection = x.Intersect(y);
Since the last one is defined as an extension on IEnumerable<T>
, it works on the more general case as well. Just be aware that it might not be as optimized for performance as HashSet<T>.IntersectWith
, since it needs to be able to work on all enumerables.
Upvotes: 3