Question

I'm using a HashSet<T> to store a collection of objects. These objects already have a unique ID of System.Guid, so I'd rather the HashSet<> just use that existing ID rather then trying to figure out itself how to hash the object. How do I override the build in hashing and force my program to use the build in ID value as the hash value?

Also say I know the Guid of an object in my HashSet<>, is there a way to get an object from a HashSet<T> based on this Guid alone? Or should I use a dictionary instead.

Was it helpful?

Solution

A HashSet<> is not based a key/value pair, and provides no "by key" access - it is just a set of unique values, using the hash to check containment very quickly.

To use a key/value pair (to fetch out by Guid later) the simplest option would be a Dictionary<Guid,SomeType>. The existing hash-code on Guid should be fine (although if you needed (you don't here) you can provide an IEqualityComparer<T> to use for hashing.

OTHER TIPS

Override the GetHashCode() method for your object.

Of course, there's a slight wrinkle here... GUIDs are larger than int32s, which .NET uses for hashcodes.

Why do you need to override this? seems like perhaps a premature optimization.

Yeah, just use a dictionary. Once you develop your application, go through a performance tuning phase where you measure the performance of all your code. If and only If this hashing function shows as being your largest drain should you consider a more performant data structure (if there is one anyways) :-)

Try looking into System.KeyedCollection. It allows you to embed the knowledge of the key field into your collection implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top