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

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

问题描述

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

以下code不为工作b 是不同的对象实例。

  INT [] A = INT新[] {1,2,3};
 INT [] B =新INT [] {1,2,3};
 字典< INT [],字符串> DIC =新词典< INT [],字符串>();
 dic.Add(一,哈哈);
 字符串输出= DIC [B]。


解决方案

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

 公共类MyEqualityComparer:&的IEqualityComparer LT; INT [] GT;
{
    公共布尔等于(INT []×,INT [] Y)
    {
        如果(x.Length!= y.Length)
        {
            返回false;
        }
        的for(int i = 0; I< x.Length;我++)
        {
            如果(X [I]!= Y [I])
            {
                返回false;
            }
        }
        返回true;
    }    公众诠释GetHash code(INT [] OBJ)
    {
        INT结果= 17;
        的for(int i = 0; I< obj.Length;我++)
        {
            未选中
            {
                结果=结果* 23 + OBJ [I]
            }
        }
        返回结果;
    }
}

然后通过它可以在创建字典:

 词典< INT [],字符串> DIC
    =新字典< INT [],字符串>(新MyEqualityComparer());

注:此处获得的散列code的计算:
<一href=\"http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethash$c$c\">What是一个重写System.Object.GetHash code最好的算法?

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?

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

解决方案

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());

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

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

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