Linq OrderBy(Byte [])值 [英] Linq OrderBy(Byte[]) values

查看:68
本文介绍了Linq OrderBy(Byte [])值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    }

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

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.

我该如何对OrderBy byte []值进行处理?

What can I do to OrderBy byte[] values?

推荐答案

数组具有可变长度(因为它是SQL Server层次结构ID),所以您绝对需要创建自定义 IComparer<byte[]> 实现.

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.

逻辑很简单:

  • 将每个数组的前n个字节逐字节进行比较,其中n是两个数组中较小的一个中的字节数.如果检测到任意字节之间存在差异,则返回不同字节的比较结果.
  • 如果前n个字节相等,则返回两个数组的长度比较.
  • Compare the first n bytes of each array byte-for-byte, where n is 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.
  • If the first n bytes are equal, return the comparison of the lengths of the two arrays.

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

This way, given a set of data like so:

00 01 02
00 01
01

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

When sorted, the results you'll get are:

00 01
00 01 02
01

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

That said, this is what your IComparer<byte[]> implementation will look like:

// 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;
    }
}

顺便说一句,如果保证字节数组的长度相同,则可以动态创建order by子句,按第一个元素排序,然后按第二个元素排序,依此类推,诸如此类:

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:

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;
}

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

And then you can simply call it like so:

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

这篇关于Linq OrderBy(Byte [])值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆