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

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

System.DirectoryServices Search Performance – Part 1

System.DirectoryServices Search Performance – Part 1

System.DirectoryServices Search Performance – Part 1 November 17th, 2008 NOTE: This post is part of a series. At Silicon...

Dell E4300 – No Application Key

Dell E4300 – No Application Key

Dell E4300 – No Application Key

Windows 2003 Folder Quota’s Command Line Management

Windows 2003 Folder Quota’s Command Line Management

Windows 2003 Folder Quota’s Command Line Management October 23rd, 2008 One of my customers has a file server with...

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...