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
Got anything to say? Go ahead and leave a comment!
Popular Posts
- Using the DataSource Field with Sitecore Sublayouts
- Tame Your Sitecore Treelists
- Write to a Custom Sitecore Log with log4net
- Sitecore Upgrade Strategy
- Rendering Fully Qualified Sitecore URLs
- Sitecore Admin Pages Explained
- Managing CSS in the Sitecore Media Library
- Use Any() Instead of Count() To See if an IEnumerable Has Any Objects
- Sitecore Front-End Development Best Practices
- Scaling Sitecore Presentation Component Data Sources
Recent Comments
- Performance tuning your Sitecore installation | Agile and ALM: Software development today on A Going Live Checklist for Sitecore Websites
- Imran Saleem on Sitecore Avanced Database Crawler Occasionally Provides Null Results
- Ty Cahill on Sitecore Front-End Development Best Practices
- Sitecore Managed Sites as Virtual Folders | Fire Breaks Ice on Sitecore Item and Field Names
- Krimos on Using the DataSource Field with Sitecore Sublayouts
Sitecore Links
- .Sitecore
- Aboo Bolaky
- Alex Shyba
- Anders Dreyer
- aweber1.0
- Brian Pedersen
- Christopher Wojciech
- Coffee => Coder => Code
- Dev Sitecored²
- Everything Web
- Image0.com blog
- John West
- Learn Sitecore
- Let's do Sitecore
- Mark van Aalst
- Matthew Kenny
- Molten Core
- Project Lifecycle
- Sean Kearney
- Sebastian Patten
- Sitecore Australia
- Sitecore Blog
- Sitecore Climber
- Sitecore Development
- Sitecore Gadgets
- Techphoria414
- The Client View
- The Sitecore Experience
- Web Content Management and Delivery
Archives
- April 2013 (1)
- February 2013 (1)
- January 2013 (1)
- December 2012 (1)
- June 2012 (2)
- May 2012 (2)
- March 2012 (1)
- February 2012 (1)
- January 2012 (5)
- December 2011 (4)
- November 2011 (1)
- July 2011 (1)
- June 2011 (1)
- May 2011 (2)
- March 2011 (6)
- February 2011 (2)
- January 2011 (10)

Posted under: