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.
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
Guidlater) the simplest option would be aDictionary<Guid,SomeType>. The existing hash-code onGuidshould be fine (although if you needed (you don’t here) you can provide anIEqualityComparer<T>to use for hashing.