IComparable Byte-Array Comparison

  • Thread starter Thread starter Stephen.Schoenberger
  • Start date Start date
S

Stephen.Schoenberger

Hello,

I am trying to figure out how to make an IComparable Byte Array
Comparison class in C# and keep running into dead ends. I have read
where this isn't possible and have seen a few hints that it might be,
but wanted to ask on here if anyone had advice.

Thanks!
 
What, to compare the bytes in turn? If so, how about below (untested)?
Or do you mean something else?

Marc

public sealed class ArrayComparer<T> : IComparer<T[]> where T :
IComparable<T>
{

private ArrayComparer() { }
public static readonly ArrayComparer<T> Singleton = new
ArrayComparer<T>();

int IComparer<T[]>.Compare(T[] x, T[] y)
{
return Compare(x, y);
}

public static int Compare(T[] x, T[] y)
{
// simple cases
if (ReferenceEquals(x, y)) return 0;
if (x == null) return 1;
if (y == null) return -1;
// get the 2 lengths and the minimum
int xLen = x.Length, yLen = y.Length, len = xLen < yLen ?
xLen : yLen;
// loop and test
for (int i = 0; i < len; i++)
{
int result = x.CompareTo(y);
if (result != 0) return result; // found a difference
}
if (xLen == yLen) return 0; // same bytes and length;
comparable
return xLen < yLen ? -1 : 1; // different lengths
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top