Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An integer array as a key for Dictionary

Tags:

arrays

c#

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];
like image 616
william007 Avatar asked Feb 02 '13 15:02

william007


2 Answers

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?

like image 198
Glen Hughes Avatar answered Oct 20 '22 10:10

Glen Hughes


Maybe you should consider using a Tuple

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

According to MSDN , Tuple objects Equals method will use the values of the two Tuple objects

like image 31
Jaydeep Shil Avatar answered Oct 20 '22 11:10

Jaydeep Shil