How about something like this?
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);
}
}
This can even be extended to a generic class for comparing arrays of any type which implements IComparable<T>
:
class ArrayComparer<T> : IComparer<T[]>
where T : IComparable<T>
{
public int Compare(T[] x, T[] 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);
}
}
This will find the first element which differs between the two arrays, and return a value indicating which comes first according the types default ordering. If there are no differences, it will return a value indicating which array is shorter.