Linq OrderBy(Byte [])值

Sto*_*r01 4 c# linq

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;
    }
Run Code Online (Sandbox Code Playgroud)

我有一组对象包含我想要OrderBy的byte []属性,但是,OrderBy(byte [])抛出一个错误:

System.ArgumentException: At least one object must implement IComparable.
Run Code Online (Sandbox Code Playgroud)

我可以对OrderBy byte []值做什么?

Ree*_*sey 5

你不能byte[]直接订购,因为数组没有实现IComparable.您需要按第一个字节(即:OrderBy(f => f.sort[0])或其他适当的)进行排序,或者自己编写IComparer<byte[]>并在OrderBy的相应重载中使用它.


cas*_*One 5

正如您已经指出数组长度可变(因为它是 SQL Server 层次结构 ID),您绝对需要创建自定义IComparer<byte[]>实现。

逻辑很简单:

  • n逐字节比较每个数组的第一个字节,其中n是两个数组中较小者的字节数。当检测到任何字节之间存在差异时,返回不同字节的比较结果。
  • 如果第一个n字节相等,则返回两个数组长度的比较结果。

这样,给定一组数据,如下所示:

00 01 02
00 01
01
Run Code Online (Sandbox Code Playgroud)

排序后,您将得到的结果是:

00 01
00 01 02
01
Run Code Online (Sandbox Code Playgroud)

也就是说,这就是您的IComparer<byte[]>实现的样子:

// I could be wrong in that this is called natural order.
class NaturalOrderByteArrayComparer : IComparer<byte[]>
{
    public int Compare(byte[] x, byte[] y)
    {
        // Shortcuts: If both are null, they are the same.
        if (x == null && y == null) return 0;

        // If one is null and the other isn't, then the
        // one that is null is "lesser".
        if (x == null && y != null) return -1;
        if (x != null && y == null) return 1;

        // Both arrays are non-null.  Find the shorter
        // of the two lengths.
        int bytesToCompare = Math.Min(x.Length, y.Length);

        // Compare the bytes.
        for (int index = 0; index < bytesToCompare; ++index)
        {
            // The x and y bytes.
            byte xByte = x[index];
            byte yByte = y[index];

            // Compare result.
            int compareResult = Comparer<byte>.Default.Compare(xByte, yByte);

            // If not the same, then return the result of the
            // comparison of the bytes, as they were the same
            // up until now.
            if (compareResult != 0) return compareResult;

            // They are the same, continue.
        }

        // The first n bytes are the same.  Compare lengths.
        // If the lengths are the same, the arrays
        // are the same.
        if (x.Length == y.Length) return 0;

        // Compare lengths.
        return x.Length < y.Length ? -1 : 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果您的字节数组保证长度相同,作为替代方案,您可以动态创建 order by 子句,按第一个元素排序,然后是第二个元素,等等,如下所示:

static IEnumerable<foo> OrderBySortField(this IEnumerable<foo> items, 
    int sortLength)
{
    // Validate parameters.
    if (items == null) throw new ArgumentNullException("items");
    if (sortLength < 0) throw 
        new ArgumentOutOfRangeException("sortLength", sortLength,
            "The sortLength parameter must be a non-negative value.");

    // Shortcut, if sortLength is zero, return the sequence, as-is.
    if (sortLength == 0) return items;

    // The ordered enumerable.
    IOrderedEnumerable<foo> ordered = items.OrderBy(i => i.sort[0]);

    // Cycle from the second index on.
    for (int index = 1; index < sortLength; index++)
    {
        // Copy the index.
        int indexCopy = index;

        // Sort by the next item in the array.
        ordered = ordered.ThenBy(i => i.sort[indexCopy]);
    }

    // Return the ordered enumerable.
    return ordered;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地这样称呼它:

// You have to supply the length of the array you're sorting on.
List<foo> sortedFoo = FooSource().
    OrderBySortField(sortLength).ToList();
Run Code Online (Sandbox Code Playgroud)