How to use compound key for dictionary?

后端 未结 3 1519
太阳男子
太阳男子 2021-01-05 18:07

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 <

相关标签:
3条回答
  • 2021-01-05 18:18

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

    var key = Tuple.Create(SomeEnum.Value1, 3);
    
    0 讨论(0)
  • 2021-01-05 18:28

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-05 18:34

    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?

    0 讨论(0)
提交回复
热议问题