HashSet.IntersectWith() in C#

admin Last updated on: April 13, 2023

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
HashSetstring> group1 = new HashSetstring> 
     { "user1", "user2", "user3" };
HashSetstring> group2 = new HashSetstring> 
     { "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);
}

Related posts

Your Web Deployment is not Automated? Is deploying your website a time consuming and error prone operation? Then come...

Outlook PST Corruption Check

Outlook PST Corruption Check

Outlook PST Corruption Check May 14th, 2007 It seems like since I’ve installed Outlook 2007 (which I love) I...

SLO MSDN Event Huge Success

SLO MSDN Event Huge Success

SLO MSDN Event Huge Success

System.DirectoryServices Search Performance – Part 4

System.DirectoryServices Search Performance – Part 4

System.DirectoryServices Search Performance – Part 4 December 15th, 2008 NOTE: This post is part of a series. Evaluating Performance...

Windows Server 2008 High Availability Windows Server 2008 High Availability – Slide Deck Learn when to use and how...

Active Directory Programming for Developers Active Directory Programming for Developers – Slide Deck Active Directory Programming for Developers –...