HashSet.IntersectWith() in C#
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 usersHashSet<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 group2group1.IntersectWith(group2);
//print out users that existed in both listsforeach (string user in group1)
{Console.WriteLine(user);
}
Steve Evans has worked in the IT field for over 12 years, specializing in Microsoft technologies. He has consulted for small businesses on their IT infrastructure needs as well as worked for larger companies as a Systems Engineer. Steve has been a recipient of the Microsoft Most Valuable Professional (MVP) award for the past 3 years, and is a Technical Speaker at various industry events.







Leave a Reply