Lets say I have an object that has stringProp1, stringProp2. I wish to store each combination of stringProp1, stringProp2 in a Dictionary. Initially I was storing the key as key = stringProp1+stringProp2 but this can actually cause a bug depending on the 2 values. Is the best solution for this problem to create a custom dictionary class or is there a better way using built-in .NET classes?
Share
It does not matter what data structure you use as the key as long as the key holds the necessary information for a comparer to properly compare/hash.
You can even use your objects as keys in the dictionary and compare on any field you like with an appropriate
EqualityComparerimplementation. This one compares on two string properties using ordinal comparison:You can search for an object by creating a dummy one, filling in the string keys and using the dummy as the key for the lookup.
If you do not like this idea, or it is not feasible, just do as @Vlad said and extract the keys in a struct or class. In this case, modify the comparer to derive from
EqualityComparer<MyKeyStructOrClass>.Note that I’ve used Jon Skeet’s method for combining string hashes. It might be better than the XOR method found on MSDN. If you feel that it is steel inadequate, feel free to treat the strings with another hash implementation – Hsieh, Murmur, Bob Jenkin’s, or whatever you believe in. Here is a nice page about hash functions that actually has some C# code as well.