c# - 如何在 C# 中使用原始列表或列表作为字典的键

标签 c# dictionary

我正在尝试使用 int 数组作为 C# 中的键,但我看到的行为是出乎意料的(对我而言)。

var result = new Dictionary<int[], int>();
result[new [] {1, 1}] = 100;
result[new [] {1, 1}] = 200;

Assert.AreEqual(1, result.Count); // false is 2

List 好像也一样

var result = new Dictionary<List<int>, int>();
result[new List<int> { 1, 1 }] = 100;
result[new List<int> { 1, 1 }] = 200;

Assert.AreEqual(1, result.Count); // false is 2

我希望 Dictionary 使用 Equals 来决定 map 中是否存在 Key。事实并非如此。

有人可以解释为什么以及如何让这种行为起作用吗?

最佳答案

.NET 列表和数组没有内置的相等比较,因此您需要提供自己的:

class ArrayEqComparer : IEqualityComparer<int[]> {

    public static readonly IEqualityComparer<int[]> Instance =
        new ArrayEqComparer();

    public bool Equals(int[] b1, int[] b2) {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null | b2 == null)
           return false;
        return b1.SequenceEqual(b2);
    }

    public int GetHashCode(int[] a) {
        return a.Aggregate(37, (p, v) => 31*v + p);
    }
}

现在您可以按如下方式构建字典:

var result = new Dictionary<int[],int>(ArrayEqComparer.Instance);

关于c# - 如何在 C# 中使用原始列表或列表作为字典的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392631/

相关文章:

python - 字符串作为关键字参数,并将来自 str.partition() 输出的多个字典合并为一个字典

python - 如果内部列表中有任何元素匹配,如何从列表列表中获取列表

c# - Xamarin Studio 跨平台应用程序错误

c# - 属性更改时属性未将值传回文本框的问题

c# - 带有附属对象的列表的优点/缺点

c# - 在 WCF 中返回已经序列化的类型

python - 检查字典中是否存在键或值

c# - ASP.NET Membership C# - 如何比较现有密码/哈希

objective-c - MKCircle 叠加层未绘制在 MapView 上

java - 如何使用 java 8 将 Stream<Map<K,V>> 收集到 Map<K,List<V>> 中?