Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 735
Fiona - myaccessible.website Avatar asked Dec 07 '12 17:12

Fiona - myaccessible.website


2 Answers

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.

like image 96
Zbigniew Avatar answered Oct 22 '22 08:10

Zbigniew


This is one of those "should I use a shoe or a brick to pound a nail into the wood" questions. You should use the appropriate data structure for the job, which based on your requirement of "constructing a unique list of objects", the HashSet<T> class satisfies.

If you require the items in list format, you can always call ToList() on the set.

like image 38
Tod Hoven Avatar answered Oct 22 '22 07:10

Tod Hoven