一个整数数组作为字典的键 [英] An integer array as a key for Dictionary

查看:48
本文介绍了一个整数数组作为字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wish to have the dictionary which uses an array of integers as keys, and if the integer array has the same value (even different object instance), they will be treated as the same key. How should I do it?

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

The following code does not work as b is different object instances.

 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];

推荐答案

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

You can create an IEqualityComparer to define how the dictionary should compare items. If the ordering of items is relevant, then something like this should work:

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;
    }
}

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

Then pass it in as you create the dictionary:

Dictionary<int[], string> dic
    = new Dictionary<int[], string>(new MyEqualityComparer());

注:这里得到的hash码的计算:覆盖系统的最佳算法是什么.Object.GetHashCode?

Note: calculation of hash code obtained here: What is the best algorithm for an overridden System.Object.GetHashCode?

这篇关于一个整数数组作为字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆