c# - 从集合中删除重复的 byte[]

标签 c# duplicates distinct hashset iequalitycomparer

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

相关文章:

java - 如何检查 Java 8 Streams 中是否存在任何重复项?

sql - 将不同列的结果放入单个列中

c# - 为什么 Convert.ToDecimal(Double) 四舍五入到 15 位有效数字?

c# - 内存泄漏将 imagebrush 加载到 grid.background

c# - 通过 Java 小程序截屏

c# - 如何确定字符串是否是已安装 UWP 应用程序的 AUMID?

Python Pandas - 如果某些值为空则合并行

JavaScript setTimeout() 重复

java - 使用BigInteger longValue()将15个字符长度的字符串转换为唯一的长数字

sql - 'select distinct'返回第一个不同的值还是最后一个不同的值?