Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<string[], object[]> c# TryGetValue always return null

Tags:

c#

dictionary

I have a simple dictionary like this:

Dictionary<string[], object[]> list = new Dictionary<string[], object[]>();

I add items with:

list.Add(new string[] {"a", "a", "a"}, new object[]{ });

The problem appear when i try to get value by key

object[] values;   
if(list.TryGetValue(new string[] {"a", "a", "a"}, out values)
{  }

always return null. Seems that he cannot find this key in dictionary but as you can see there is...

Thanks for help

like image 635
Mirko Fogazzi Avatar asked Jun 27 '26 05:06

Mirko Fogazzi


1 Answers

As already answered, each array is indeed different object. By default, arrays are compared using object reference, without taking into account the actual content of the array. You can work around this by implementing your own array comparer, like this:

class ArrayComparer<T> : IEqualityComparer<T[]> {
    public bool Equals(T[] x, T[] y) {
        return ((IStructuralEquatable) x).Equals((IStructuralEquatable) y, EqualityComparer<T>.Default);
    }

    public int GetHashCode(T[] obj) {
        return ((IStructuralEquatable) obj).GetHashCode(EqualityComparer<T>.Default);
    }
}

It works using built-in Array functionality (Array implements IStructuralEquatable) to provide equality and hashcode operations which respect array elements. Then you do:

Dictionary<string[], object[]> list = new Dictionary<string[], object[]>(new ArrayComparer<string>());

And it will work even if you pass different instances or arrays. Whether you should have a dictionary where keys are arrays is a different story....

like image 124
Evk Avatar answered Jun 29 '26 19:06

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!