这可能是一个非常简单的问题。我只是想从集合中删除重复的 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