Let us start with the quiz about generic dictionary.
DictionaryWhat value will simpleDict["name1"] return?simpleDict = new Dictionary (StringComparer.OrdinalIgnoreCase);
simpleDict["name1"] = "value";
simpleDict["Name1"] = "value2";
Let's get back to using complex keys in generic dictionary.
.NET Framework provides IEqualityComparer<T> interface that can be used by dictionary to distinguish between different keys.
Imagine we have a complex class that we want to serve as a key in our dictionary.
public class ComplexKeyThe implentation of the comparer will be the following:
{
public int Part1 { get; set; }
public string Part2 { get; set; }
}
public class ComplexKeyComprarer : IEqualityComparerHaving created the comparer we can now instantiate dictionary and operate with complex keys in the same way as with simple ones.
{
public bool Equals(ComplexKey x, ComplexKey y)
{
return x.Part1.Equals(y.Part1) && x.Part2.Equals(y.Part2);
}
public int GetHashCode(ComplexKey obj)
{
return obj.Part1.GetHashCode() ^ obj.Part2.GetHashCode();
}
}
Dictionary<ComplexKey, string> complexDict =
new Dictionary<ComplexKey, string>(new ComplexKeyComprarer());
ComplexKey ck1 = new ComplexKey() { Part1 = 1, Part2 = "name1" };
ComplexKey ck2 = new ComplexKey() { Part1 = 1, Part2 = "name2" };
complexDict[ck1] = "value1";
complexDict[ck2] = "value2";
Very convenient by the way :)