整数数组作为Dictionary的键

wil*_*007 14 c# arrays

我希望有一个使用整数数组作为键的字典,如果整数数组具有相同的值(甚至是不同的对象实例),它们将被视为相同的键.我该怎么办?

以下代码b不同,因为不同的对象实例.

 int[] a = new int[] { 1, 2, 3 };
 int[] b = new int[] { 1, 2, 3 };
 Dictionary<int[], string> dic = new Dictionary<int[], string>();
 dic.Add(a, "haha");
 string output = dic[b];
Run Code Online (Sandbox Code Playgroud)

Gle*_*hes 32

您可以创建一个IEqualityComparer来定义字典应如何比较项目.如果项目的顺序是相关的,那么这样的事情应该有效:

public class MyEqualityComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] x, int[] y)
    {
        if (x.Length != y.Length)
        {
            return false;
        }
        for (int i = 0; i < x.Length; i++)
        {
            if (x[i] != y[i])
            {
                return false;
            }
        }
        return true;
    }

    public int GetHashCode(int[] obj)
    {
        int result = 17;
        for (int i = 0; i < obj.Length; i++)
        {
            unchecked
            {
                result = result * 23 + obj[i];
            }
        }
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在创建字典时传入它:

Dictionary<int[], string> dic
    = new Dictionary<int[], string>(new MyEqualityComparer());
Run Code Online (Sandbox Code Playgroud)

注意:计算这里获得的哈希码: 重写的System.Object.GetHashCode的最佳算法是什么?

  • 你为什么称它为"我的"**"EqualityComparer"?这是你的事实是无关紧要的.它应该被称为`IntArrayEqualityComparer`或类似的东西:) (4认同)
  • @ william007因为`Dictionary <,>`维护其键的哈希表,因此必须有一个尊重新的`Equals`的`GetHashCode`.出于同样的原因,`IEqualityComparer <>`接口要求你做`GetHashCode`. (2认同)

Jay*_*hil 5

也许你应该考虑使用元组

var myDictionary = new Dictionary<Tuple<int,int>, string>(); 
myDictionary.Add(new Tuple<int,int>(3, 3), "haha1"); 
myDictionary.Add(new Tuple<int,int>(5, 5), "haha2"); 
Run Code Online (Sandbox Code Playgroud)

根据MSDN,Tuple对象Equals方法将使用两个Tuple对象的值

  • 无法扩展到不同长度的数组 (2认同)
  • @bkw1491 从 C# 7 开始,您可以将其简化为 var myDictionary = new Dictionary&lt;(int,int), string&gt;(); myDictionary.Add((5, 5), "哈哈2"); (2认同)