6

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.

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
user1213488
  • 473
  • 2
  • 7
  • 19
  • Step through each element in log1 and compare them to each of the elements in log2, that's how I would do it. Although I'm not sure how you would access individual elements. I'm guessing you might be able to construct a foreach (string s in log1) for it? Note: I've never used the HashSet type, and I'm guessing – Jamie Taylor May 17 '12 at 12:44

3 Answers3

15

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));
dtb
  • 213,145
  • 36
  • 401
  • 431
7

Using LINQ:

log1.Intersect(log2).Any()

See Intersect and Except on MSDN.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

Have you seen the ExceptWith function?

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

bdukes
  • 152,002
  • 23
  • 148
  • 175
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445