其他分享
首页 > 其他分享> > 字典Dictionary添加重复键值、添加相同的key

字典Dictionary添加重复键值、添加相同的key

作者:互联网

如果想要往Dictionary里面添加相同的Key需要重写IEqualityComparer接口中的Equals方法,代码如下

internal class DicComparer : IEqualityComparer<string>
    {
        public bool Equals(string? x, string? y)
        {
            return x != y;  
        }

        public int GetHashCode([DisallowNull] string obj)
        {
            return obj.GetHashCode();
        }
    }

使用说明

var dic = new Dictionary<string, string>(new DicComparer());
dic.Add("dic", "1");
dic.Add("dic", "2");
dic.Add("dic", "3");
foreach (var item in dic)
{
    Console.WriteLine($"key值为{item.Key},value为{item.Value}");
}

 

输出结果

key值为dic,value为1
key值为dic,value为2
key值为dic,value为3

 

标签:Dictionary,值为,value,dic,Add,添加,键值,key
来源: https://www.cnblogs.com/jiatree/p/16381481.html