2

这可能是一个非常简单的问题。我只是想从集合中删除重复的 byte[]s。

由于默认行为是比较引用,因此我认为创建 IEqualityComparer 会起作用,但事实并非如此。

我尝试过使用 HashSet 和 LINQ 的 Distinct()。

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

namespace cstest
{
    class Program
    {
        static void Main(string[] args)
        {
            var l = new List<byte[]>();
            l.Add(new byte[] { 5, 6, 7 });
            l.Add(new byte[] { 5, 6, 7 });
            Console.WriteLine(l.Distinct(new ByteArrayEqualityComparer()).Count());
            Console.ReadKey();
        }
    }

    class ByteArrayEqualityComparer : IEqualityComparer<byte[]>
    {
        public bool Equals(byte[] x, byte[] y)
        {
            return x.SequenceEqual(y);
        }

        public int GetHashCode(byte[] obj)
        {
            return obj.GetHashCode();
        }
    }
}

输出:

2
4

1 回答 1

5

GetHashCode将由 使用,Distinct并且不会“按原样”工作;尝试类似:

int result = 13 * obj.Length;
for(int i = 0 ; i < obj.Length ; i++) {
    result = (17 * result) + obj[i];
}
return result;

它应该为哈希码提供必要的相等条件。

就个人而言,我也会展开性能平等测试:

if(ReferenceEquals(x,y)) return true;
if(x == null || y == null) return false;
if(x.Length != y.Length) return false;
for(int i = 0 ; i < x.Length; i++) {
    if(x[i] != y[i]) return false;
}
return true;
于 2010-07-25T14:39:39.030 回答