Tuesday, June 23, 2009

Complex Keys In Generic Dictionary

Let us start with the quiz about generic dictionary.

Dictionary simpleDict = new Dictionary(StringComparer.OrdinalIgnoreCase);
simpleDict["name1"] = "value";
simpleDict["Name1"] = "value2";
What value will simpleDict["name1"] return?

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 ComplexKey
{
public int Part1 { get; set; }
public string Part2 { get; set; }
}
The implentation of the comparer will be the following:
public class ComplexKeyComprarer : IEqualityComparer
{
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();
}
}
Having created the comparer we can now instantiate dictionary and operate with complex keys in the same way as with simple ones.
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 :)

4 comments:

  1. Hello!
    I came across your blog while searching for information on HTTP proxies in .NET. How's yours coming along? Mine is causing a complete slowdown in page surfing.. google's page takes over a minute to load when using the proxy. Thought maybe we could compare notes.

    -Dan

    ReplyDelete
  2. I have implemented several of them as the internal projects.

    Did you perform an investigation what is causing slowdown?
    Minute slowdown can indicate a bug or some major design problem.

    Can you share details about it for me to help you?

    ReplyDelete
  3. Vadym,
    Thanks for the quick reply and the offer to help.

    I guess I was just hoping that you had a simple proxy class you'd be willing to share that I could use as a starting point for my own project. It would save a lot of time - instead of spending a bunch of time writing networking code I could jump to the meat of the project. I'm not trying to be lazy.. its just a personal project that I don't have a lot of time for, so the more time I can devote to implementation instead of networking is a plus for me.

    If you don't have a suitable class - or do not wish to share it, I completely understand.

    I'm not sure if you are in the U.S. or not, if you are then I hope you enjoy your Labor Day! If not, hen have a great weekend!

    -Dan

    ReplyDelete
  4. GhostInAK,

    There was a good proxy class in the mentalis.org web site.

    Check this url http://www.mentalis.org/soft/projects/proxy/

    ReplyDelete