Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary of arrays

Tags:

c#

dictionary

Can I use C# Dictionary on classes like arrays??

Dictionary<double[],double[]>

I am afraid that it will not be able to tell when arrays are equal...

EDIT:
Will the hashing method in the dictionary take well care of arrays? or just hashing their references?

like image 822
Betamoo Avatar asked May 25 '10 20:05

Betamoo


2 Answers

For array keys, the dictionary willuse the references for hashing and equality, which probably isn't what you want. This leaves you with two choices: implement a wrapper class for double[], or (better) write something that implements IEqualityComparer and pass it to the Dictionary<T, T> constructor.

like image 167
JSBձոգչ Avatar answered Oct 06 '22 00:10

JSBձոգչ


Only the array references will be compared. In the following example, the dictionary will have 2 entries even though arrays a and b have the same number of entries and the entry values are equal:

double[] a = new[] { 1.0, 2.1, 3.2 };
double[] b = new[] { 1.0, 2.1, 3.2 };

Dictionary<double[], double[]> d = new Dictionary<double[], double[]>();

d[a] = new [] { 1.1 };
d[b] = new [] { 2.2 };

Console.WriteLine(d.Count);
Console.WriteLine(d[b][0]);
like image 22
Daniel Renshaw Avatar answered Oct 05 '22 22:10

Daniel Renshaw