public class foo {
int ID { get; set; }
byte[] sort { get; set; }
}
public class barMaster {
public void FooSource() {
return List<foo> FromDataSource;
}
public void display() {
List<foo> sortedFoo = FooSource().OrderBy(f => f.sort);
UIElement = sortedFoo;
}
I have a set of objects that contain a byte[] property that I want to OrderBy, however, OrderBy(byte[]) throws an error:
System.ArgumentException: At least one object must implement IComparable.
What can I do to OrderBy byte[] values?
As you’ve indicated that the arrays are of variable length (as it’s a SQL Server hierarchy ID), you absolutely need to create a custom
IComparer<byte[]>implementation.The logic is simple:
nbytes of each array byte-for-byte, wherenis the number of bytes in the smaller of the two arrays. When a difference is detected between any byte, return the result of the comparison of the different bytes.nbytes are equal, return the comparison of the lengths of the two arrays.This way, given a set of data like so:
When sorted, the results you’ll get are:
That said, this is what your
IComparer<byte[]>implementation will look like:As an aside, if your byte arrays were guaranteed to be the same length, as an alternative you can dynamically create the order by clause, sorting by the first element, then the second, etc, etc, like so:
And then you can simply call it like so: