I want to compare byte arrays used as keys in a SortedList
public SortedList<byte[], string> myList = new SortedList<byte[], string>();
the problem is, that I cant add entries into myList, because .NET doesnt know how to compare two elements of the list ("Error comparing two elements in array"):
byte[] bytearray = {0,0,25,125,250}; // Example
string description = "Example Value";
myList.Add(bytearray, description);
After a bit of googling I read something about implementing my own IComparer Class. I've searched further but didn't found anything about an IComparer implementation for byte arrays. Do you have any idea how to accomplish this?
Quick Edit: Thanks for the answers! I've implemented the IComparer from the answer provided:
class ByteComparer : IComparer<byte[]>
{
public int Compare(byte[] x, byte[] y)
{
var len = Math.Min(x.Length, y.Length);
for (var i = 0; i < len; i++)
{
var c = x[i].CompareTo(y[i]);
if (c != 0)
{
return c;
}
}
return x.Length.CompareTo(y.Length);
}
}
And calling it with:
public SortedList<byte[], string> myList = new SortedList<byte[], string>(new ByteComparer());