Reputation:
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
Upvotes: 0
Views: 865
Reputation: 3681
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.
Upvotes: 1
Reputation: 1500835
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;
}
...
Upvotes: 6