user1213488
user1213488

Reputation: 503

Compare two hashsets?

I have two hashsets like this:

HashSet<string> log1 = new HashSet<string>(File.ReadLines("log1.txt"));
HashSet<string> log2 = searcher(term);

How would I compare the two?

I want to make sure that log2 does not contain any entries from log1. In other words, I want to remove all(if any), items that log1 has inside log2.

Upvotes: 6

Views: 7798

Answers (3)

Daniel A. White
Daniel A. White

Reputation: 190945

Have you seen the ExceptWith function?

Removes all elements in the specified collection from the current HashSet object.

Upvotes: 1

dtb
dtb

Reputation: 217293

To remove all items from log2 that are in log1, you can use the HashSet<T>.ExceptWith Method:

log2.ExceptWith(log1);

Alternatively, you can create a new HashSet<T> without modifying the two original sets using the Enumerable.Except Extension Method:

HashSet<string> log3 = new HashSet<string>(log2.Except(log1));

Upvotes: 15

Oded
Oded

Reputation: 499002

Using LINQ:

log1.Intersect(log2).Any()

See Intersect and Except on MSDN.

Upvotes: 7

Related Questions