Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use compound key for dictionary?

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?

like image 432
Captain Comic Avatar asked Oct 20 '10 09:10

Captain Comic


2 Answers

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?

like image 187
Onkelborg Avatar answered Sep 30 '22 02:09

Onkelborg


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;
    }
}
like image 26
Rob Levine Avatar answered Sep 30 '22 01:09

Rob Levine