user10609288
user10609288

Reputation:

how to contains char[] key in Dictonary c#

Hi everyone i have a same structure:

Dictionary<char[], char> MyDictonary = new Dictionary<char[], char>();

First value is key, and i want to check my key f.e.

 char[] array = currentCharecter(this is a string).ToCharArray();
 bool isContains= MyDictonary.ContainsKey(array);

I know that i can't complane chars[] by == and need to use special method. Equal== only compares the references of the two arrays, not their items, it will always return false.

I must to compare the elements of one array to the elements of the other. like method SequenceEqual . But i dont understand how to use it on it. Heed help. Thanks.

Upvotes: 0

Views: 477

Answers (1)

Peter Csala
Peter Csala

Reputation: 22819

All you need to do is to define a custom class which defines how to compare two char arrays. You can do this by implementing the IEqualityComparer<char[]> interface, like this:

class CharArrayComparer : IEqualityComparer<char[]>
{
    public bool Equals(char[] x, char[] y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(char[] obj)
    {
        unchecked
        {
            int hash = 17;
            foreach (char character in obj)
            {
                hash = hash * 31 + character.GetHashCode();
            }

            return hash;
        }
    }
}

Then an instance of this class needs to be passed to the constructor of the Dictionary.
So, the usage would look like this:

var testDictionary = new Dictionary<char[], char>(new CharArrayComparer())
{
    { "Apple".ToCharArray(), 'A' },
    { "Banana".ToCharArray(), 'B' },
    { "Citron".ToCharArray(), 'C' },

};

Console.WriteLine(testDictionary.ContainsKey("Apple".ToCharArray())); //true
Console.WriteLine(testDictionary.ContainsKey("apple".ToCharArray())); //false

Upvotes: 2

Related Questions