How to use compound key for dictionary?

后端 未结 3 1536
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    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;
        }
    }
    

提交回复
热议问题