Filter a List to Unique Objects with a HashSet

LINQ provides a number of interesting ways to filter generic lists in C#. As with most programming tasks, there are many options, but not all options are equal. An easy way to filter a list of many items to a list of unique items from the original list is to use a HashSet. A HashSet is a set, and therefore by definition only contains unique objects. To find unique objects, simply iterate over the original list adding each item to the HashSet. The HashSet’s Add method will automatically check if it already contains the item and will guarantee unique items in the set. You should make sure you correctly define the Equals method in your class as well.

List<string> allItems = GetAll();
var uniqueItems = HashSet<string>();

allItems.ForEach(i => uniqueItems.Add(i));

uniqueItems.ToList<string>(); // now a list of unique strings


Mark Ursino

Mark is Sr. Director at Rightpoint and a Sitecore MVP.


Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.