C# 作为字典键的整数数组

C# 作为字典键的整数数组,c#,arrays,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"); strin

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

以下代码不起作用,因为
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];
int[]a=新的int[]{1,2,3};
int[]b=新的int[]{1,2,3};
Dictionary dic=新字典();
dic.添加(a,“哈哈”);
字符串输出=dic[b];

您可以创建一个
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;
    }
}
公共类MyEqualityComparer:IEqualityComparer
{
公共布尔等于(int[]x,int[]y)
{
如果(x.长度!=y.长度)
{
返回false;
}
对于(int i=0;i
然后在创建字典时传入:

Dictionary<int[], string> dic
    = new Dictionary<int[], string>(new MyEqualityComparer());
字典
=新字典(new MyEqualityComparer());
注:此处获得的哈希码计算:

如果您不关心实际的散列,最简单的方法可能就是将数组转换为字符串

dic.Add(String.Join("",a), "haha");

也许你应该考虑使用元组

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"); 
var myDictionary=newdictionary();
添加(新元组(3,3),“haha1”);
添加(新元组(5,5),“haha2”);

根据,Tuple objects
Equals
方法将使用两个Tuple objects的值

Duplicate:这与
List
为什么需要GetHashCode而不是Equal操作符有关?@william007因为
字典
维护其键的哈希表,因此,必须有一个尊重新的
等于
GetHashCode
。出于同样的原因,
IEqualityComparer
接口要求您执行
GetHashCode
。为什么称它为
My
EqualityComparer
?它是你的这一事实无关紧要。为什么GetHashCode()不能简单地返回obj.GetHashCode()?@SimonHewitt,因为哈希代码必须遵循这样的规则:如果两个对象为
x.Equals(y)
返回true,那么
x.GetHashCode()==y.GetHashCode()
也必须为true。使用
obj.GetHashCode()
将无法实现这一承诺,因为您有一个用于比较的
Equals
的自定义实现,因此您将得到
x.Equals(y)==true
x.GetHashCode()!=y、 GetHashCode()
在正确的hashcode实现中是非法的..不可扩展到不同长度的数组sdic.Add(String.Join(“,new int[]{1,2,3}),“haha”);dic.Add(String.Join(“,newint[]{12,3}),“this fails”);但它将使用分隔符