c# - IEqualityComparer 未按预期工作

标签 c# .net linq iequalitycomparer

我有一个 List存储在我的计算机上的文件路径。我的目的是先过滤掉同名的文件,再过滤掉大小相同的文件。
为此,我创建了两个类来实现 IEqualityComparer<string> , 并实现 EqualsGetHashCode方法。

var query = FilesList.Distinct(new CustomTextComparer())
                     .Distinct(new CustomSizeComparer()); 

这两个类的代码如下:-

public class CustomTextComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        if (Path.GetFileName(x) == Path.GetFileName(y))
        {
            return true;
        }
        return false; 
    }
    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}
public class CustomSizeComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        if (new FileInfo(x).Length == new FileInfo(y).Length)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

但是代码不起作用。

它没有抛出任何异常,也没有任何编译器错误,但问题是代码不起作用(不排除重复文件)。

那么,我该如何解决这个问题呢?我可以做些什么来使代码正常工作。

最佳答案

更改您的 GetHashCode 以处理比较值。 IE。对于您的尺寸比较器:

public int GetHashCode(string obj)
{
    return FileInfo(x).Length.GetHashCode();
}

另一个:

public int GetHashCode(string obj)
{
    return Path.GetFileName(obj).GetHashCode();
}

根据这个答案 - What's the role of GetHashCode in the IEqualityComparer<T> in .NET? ,首先评估哈希码。 Equals 在发生碰撞时被调用。

显然,处理 FileInfo 而不是字符串是明智的。

所以也许:

FileList.Select(x => new FileInfo(x))
        .Distinct(new CustomTextComparer())
        .Distinct(new CustomSizeComparer());

当然,您必须更改比较器以处理正确的类型。

关于c# - IEqualityComparer 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21402465/

相关文章:

c# - 具有不同数据类型数组作为值的字典

c# - 将数组从一个按钮传递到另一个按钮

c# - 使用 IStringLocalizer<T> 进行单元测试类

c# - 限制数据查询,只获取最后 1000 行

C# - 使用属性名称作为字符串按属性排序的代码

c# - 删除 div 之间的间距,bootstrap

c# - 如何修复 WPF 错误 : "Program does not contain a static ' Main' method suitable for an entry point"?

c# - 如何使用 BinaryReader 和 BinaryWriter 创建自己的二进制序列化器?

c# - 如何在 `RoleEntryPoint.OnStop()` 方法中优雅地关闭 mongod

c# - Linq Navigation Properties complex where ID in (select id from...)