这可能是一个非常简单的问题。我只是想从集合中删除重复的 byte[]。
由于默认行为是比较引用,我认为创建 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
最佳答案
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;
关于c# - 从集合中删除重复的 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3329574/