2

I want to compare byte arrays used as keys in a SortedList

public SortedList<byte[], string> myList = new SortedList<byte[], string>();

the problem is, that I cant add entries into myList, because .NET doesnt know how to compare two elements of the list ("Error comparing two elements in array"):

byte[] bytearray = {0,0,25,125,250}; // Example 
string description = "Example Value";
myList.Add(bytearray, description);

After a bit of googling I read something about implementing my own IComparer Class. I've searched further but didn't found anything about an IComparer implementation for byte arrays. Do you have any idea how to accomplish this?

Quick Edit: Thanks for the answers! I've implemented the IComparer from the answer provided:

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

And calling it with:

    public SortedList<byte[], string> myList = new SortedList<byte[], string>(new ByteComparer());
4

3 回答 3

4

这样的事情怎么样?

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

这甚至可以扩展到一个泛型类,用于比较实现的任何类型的数组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);
    }
}

这将找到两个数组之间不同的第一个元素,并返回一个值,指示根据类型默认排序哪个先出现。如果没有差异,它将返回一个值,指示哪个数组更短。

于 2013-10-30T23:26:37.497 回答
1

您需要创建一个实现IComparer<byte[]>接口的类。这个接口有一个方法 - public int Compare(byte[] first, byte[] second). 该方法应返回负 int if first < second、 0 iffirst == second和正 int if first > second。您需要弄清楚应用程序中的<==>含义,并相应地编写方法。

于 2013-10-30T23:27:25.180 回答
0

这真的取决于你的逻辑流程。byte array a小于是什么意思byte array b?你应该比较什么?无论如何,您只需要实现一种简单的方法:int Compare(byte[] x, byte[] y)

于 2013-10-30T23:31:12.433 回答