tags:

views:

244

answers:

4

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.

+1  A: 

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) :-)

Joel Martinez
+1  A: 

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

Gord
be careful here as the KeyedCollection uses a dictionary by default internally :-P From the documentation"By default, the KeyedCollection<TKey, TItem> includes a lookup dictionary. When an item is added to the KeyedCollection<TKey, TItem>, the item's key is extracted once and saved in the lookup dictionary for faster searches."
Joel Martinez
+4  A: 

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.

Marc Gravell
+2  A: 

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.

R. Bemrose
That won't help you "get an object from a HashSet based on this Guid alone"
Marc Gravell
@Marc: The first part of the question stated "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." Overriding HashSet does so. Of course, there is the slight problem that a GUID is four times the size of an int32.
R. Bemrose