简体   繁体   中英

Declaring Inner dictionary comparer C#

I have a dictionary as follows

Dictionary<ulong, Dictionary<byte[], byte[]>> Info;

And the inner dictionary holds a byte[] array as a key.

I am unable to understand how to declare the constructor for a the Info dictionary. For the inner key comparison I have ByteArrayComparer ,

  public class ByteArrayComparer : IEqualityComparer<byte[]> 
    {
        public bool Equals(byte[] left, byte[] right)
        {
            if (left == null || right == null)
            {
                return left == right;
            }
            if (left.Length != right.Length)
            {
                return false;
            }
            for (int i = 0; i < left.Length; i++)
            {
                if (left[i] != right[i])
                {
                    return false;
                }
            }
            return true;
        }
        public int GetHashCode(byte[] key)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            int sum = 0;
            foreach (byte cur in key)
            {
                sum += cur;
            }
            return sum;
  }
}

Which I picked up from SO Here

Please advise

The specification for the comparer wouldn't be part of the Info initialization directly - it would be when you create a value to put in the outer dictionary. For example:

// It's stateless, so let's just use one of them.
private static readonly IEqualityComparer<byte[]> ByteArrayComparerInstance
    = new ByteArrayComparer();

Dictionary<ulong, Dictionary<byte[], byte[]>> Info
    = new Dictionary<ulong, Dictionary<byte[], byte[]>();

....

...
Dictionary<byte[], byte[]> valueMap;

if (!Info.TryGetValue(key, out valueMap))
{
    valueMap = new Dictionary<byte[], byte[]>(ByteArrayComparerInstance);
    Info[key] = valueMap;
}
...

When created your Info doesn't have any dictionaries inside so u can't realy define comparere at that step. You have to do this for each item added into Info object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM