我希望有一个使用整数数组作为键的字典,如果整数数组具有相同的值(甚至是不同的对象实例),它们将被视为相同的键.我该怎么办?
以下代码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的最佳算法是什么?
也许你应该考虑使用元组
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对象的值
| 归档时间: |
|
| 查看次数: |
15084 次 |
| 最近记录: |