Best way to create a unique list of objects in C #

I am wondering if it will be easier to follow one pattern to create a unique list of objects in C #:

Option 1

  • Add all items to the general list.
  • Call a list. Accounting function on it

Option 2

  • Iterate over each item
  • Check if the item exists in the list, and if not, add it
+4
source share
3 answers

You can use HashSet<T> :

The HashSet class provides high-performance dialing operations. A set is a collection that does not contain repeating elements and whose elements do not have a special order.

You can provide a custom IEqualityComparer<T> through the constructor.

+16
source

This is one of those, "I have to use shoes or a brick to fix a nail into the forest." You must use the appropriate data structure for the job, which is based on your requirement of "creating a unique list of objects", the HashSet<T> class satisfies.

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

+3
source

If you are concerned about the performance of searching for unique elements, use Dictionary<TKey, TVale> . In addition, the dictionary requires unique keys, so you will never have duplicates.

0
source

All Articles