Filter a List to Unique Objects with a HashSet

Jan 13, 2011 by Mark Ursino    No Comments    Posted under: ASP.NET

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

Got anything to say? Go ahead and leave a comment!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Categories