HashSet.IntersectWith() in C#

April 2nd, 2009

I realize that real developers have been aware of this for years.  However I think it’s important to remember that I am not a real developer.  I am primarily an IT Pro who happens to be able to fake being a developer in the right circumstances.  I should also note that I’m writing this blog post almost exclusively so I’ll have a chance of remembering this in 3 months when I need to use it.

I ran across HashSets (introduced in .Net 3.5) recently and immediately realized where they would come in incredibly handy.  Especially as an IT Pro you often have two sets of lists of users and you need to find the users that exist in both lists.

//artificially create two lists of users
HashSet<string> group1 = new HashSet<string> 
     { "user1", "user2", "user3" };
HashSet<string> group2 = new HashSet<string> 
     { "user3", "user4", "user5" };
 
//modify group1 to contain only 
//items that also exist in group2
group1.IntersectWith(group2);
 
//print out users that existed in both lists
foreach (string user in group1)
{
     Console.WriteLine(user);
}

Leave a Reply