c# – How to use compound key for dictionary? – Education Career Blog

I need to arrange sort of dictionary where the key would be a pair of enum and int
and value is object. So I want to map a pair to some object.

One option would be

public enum SomeEnum
{
 value1, value2
}

class Key
{
  public SomeEnum;
  public int counter;  

  // Do I have to implement Compare here?
}

Dictionary<SomeEnum, object> _myDictionary;

Another option would convert enum and int to some unique key.

string key = String.Format("{0}/{1}", enumValue, intValue)

That approach requires string parsing, a lot of extra work.

How to make it easily?

,

I would go with something similar to

public enum SomeEnum
{
 value1, value2
}

public struct Key
{
  public SomeEnum;
  public int counter;  
}

Dictionary<Key, object>

I think that would make it?

,

If you are going to put this in a dictionary, then you will need to make sure you implement a meaningful .Equals and .GetHashCode or the dictionary will not behave correctly.

I’d start off with something like the following for the basic compound key, and then implement a custom IComparer to get the sort order you need.

public class MyKey
{
    private readonly SomeEnum enumeration;
    private readonly int number;

    public MyKey(SomeEnum enumeration, int number)
    {
        this.enumeration = enumeration;
        this.number = number;
    }

    public int Number
    {
        get { return number; }
    }

    public SomeEnum Enumeration
    {
        get { return enumeration; }
    }

    public override int GetHashCode()
    {
        int hash = 23 * 37 + this.enumeration.GetHashCode();
        hash = hash * 37 + this.number.GetHashCode();

        return hash;
    }

    public override bool Equals(object obj)
    {
        var supplied = obj as MyKey;
        if (supplied == null)
        {
            return false;
        }

        if (supplied.enumeration != this.enumeration)
        {
            return false;
        }

        if (supplied.number != this.number)
        {
            return false;
        }

        return true;
    }
}

,

If you are using C# 4.0, you could use the Tuple class.

var key = Tuple.Create(SomeEnum.Value1, 3);

Leave a Comment