Best way for constructing a unique list of objects in C#

Fiona - myaccessible.website picture Fiona - myaccessible.website · Dec 7, 2012 · Viewed 7.9k times · Source

I'm wondering whether it will be quicker to follow one pattern or another for constructing a unique list of objects in C#:

Option 1

  • Add all the items into a generic list
  • Call the list.Distinct function on it

Option 2

  • Iterate over each item
  • Check whether the item already exists in the list and if not add it

Answer

Zbigniew picture Zbigniew · Dec 7, 2012

You can use HashSet<T>:

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

You can provide custom IEqualityComparer<T> via constructor.