Whether a Dictionary can have Array as Key?

Am Facing a problem in Dictionaries. Whether an Array can be a Key of a Value???

Dictionary<string[], int> di = new Dictionary<string[], int>();
di.Add(new string[]
{
    "1","2"
}, 1);

di.Add(new string[]
{
    "2","3"
}, 2);

MessageBox.Show(di[new string[] { "2", "3" }].ToString()); // Here KeyNotFoundException occurred.

Why Exception?

Answers


By default only references of the arrays would be compared, so you either have to

  1. provide a custom IEqualityComparer<string[]> or
  2. use a Tuple<string, string> as key instead ( since you only have two strings)

Here's a similar question's answer which shows how to create a custom comparer for the Dictionary- constructor.


No, actually you should not use arrays as a Dictionary<> Key; Dictionary<> when works with keys uses their hash codes which are computed as addresses:

String[] a = new[]{"1", "2"}; 
String[] b = new[]{"1", "2"}; 

a.GetHashCode() == b.GetHashCode(); // <- false

Arrays a and b have different addresses, and so different hash codes that's why

di.Add(a, 1); 
di[b]; // <- error since a.GetHashCode() != b.GetHashCode() 

Because a the Equals and GetHashCode functions of an array don't compare the content but the reference of the array himself.


Need Your Help

pass PHP variable values to view page in YII

javascript php yii

I am new to Yii, I wan to pass PHP variable value from my controller to view. can someone please help on this. I am stuck here. I must compute this variable in auto complete field using JavaScript.

MS Access 2003 - Combine last record of multiple tables into one query or table?

ms-access vba access-vba ms-access-2003

I have a couple of tables that are transaction tables, and I would like to make a simple pivot chart for comparative balances....which happen to be the last record of each of these tables in a field