登录

c# Dictionary 自定义类型的key 如何判断是否存在

public class DicConfigKey
    {
        public string ID { get; set; }
        public string TypeID { get; set; }
    }
Dictionary<DicConfigKey, string> dic = new Dictionary<DicConfigKey, string>();
            dic.Add(new DicConfigKey { ID = "1", TypeID = "010" }, "test1");
            dic.Add(new DicConfigKey { ID = "1", TypeID = "020" }, "test2");
            dic.Add(new DicConfigKey { ID = "2", TypeID = "020" }, "test3");
            DicConfigKey key = new DicConfigKey() { ID = "2", TypeID = "020" };
            //bool flag = dic.Keys.Contains(key);
            bool flag = dic.ContainsKey(key);

如上代码,Dictionary中自定义类型的键Key,如何判断key是否存在呢,dic.Keys.Contains和dic.ContainsKey都返回false

问题已解决,重写DicConfigKey的Equals和GetHashCode方法即可,代码如下

public class DicConfigKey
    {
        public string ID { get; set; }
        public string TypeID { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == this)
                return true;
            if (!(obj is DicConfigKey))
                return false;
            var dicconfikey = (DicConfigKey)obj;
            return ID == dicconfikey.ID && TypeID == dicconfikey.TypeID;
        }

        public override int GetHashCode()
        {
            return (ID + TypeID).GetHashCode();
        }
    }


# C#
高洛峰 高洛峰 2715 天前 724 次浏览

全部回复(1) 我要回复

  • 三叔

    三叔2016-11-12 10:58:02

    http://stackoverflow.com/questions/16472159/using-a-class-versus-struct-as-a-dictionary-key

    换struct

    或者使用GetHashCode/Equals自己来写对比规则


    回复
    0
  • 取消 回复 发送