Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether a Dictionary can have Array as Key?

Tags:

c#

dictionary

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?

like image 928
Gokul E Avatar asked Jan 26 '26 17:01

Gokul E


1 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.

like image 200
Tim Schmelter Avatar answered Jan 29 '26 10:01

Tim Schmelter