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

3

6

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
Pyrazole answered 7/12, 2012 at 17:9 Comment(0)
T
19

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.

Throaty answered 7/12, 2012 at 17:13 Comment(3)
Thanks, though it's a quote from MSDN.Throaty
A HashSet<T> isn't actually a list -- it doesn't preserve order and doesn't provide indexed access. (Not that the OP seems to be aware of the distinction, either.)Viddah
@DavidMoles indeed HashSet<T> isn't a List<T>. It seems that OP simply wasn't aware of HashSet, so this is why I've proposed it as a solution. Because of this, I think, that we can assume that word "list" (in this case) means something being a collection of items.Throaty
P
4

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.

Priapitis answered 7/12, 2012 at 17:16 Comment(2)
Actually it is a Shoe or glass bottle.Unscientific
A HashSet<T> isn't actually a list -- it doesn't preserve order and doesn't provide indexed access. (Not that the OP seems to be aware of the distinction, either.)Viddah
I
0

If you are concerned about the performance of looking up unique items, use a Dictionary<TKey, TVale>. Also, a dictionary requires unique keys, so you will never have duplicates.

Indoor answered 7/12, 2012 at 17:11 Comment(2)
Based on the description he doesn't have a key-value relationship, so instead of a Map (one implementation in C# is a Dictionary) he needs a Set (such as a HashSet).Lugsail
Indeed, I forgot about Hashset.Indoor

© 2022 - 2024 — McMap. All rights reserved.