IEqualityComparer not working as intended

后端 未结 3 1855
梦毁少年i
梦毁少年i 2021-01-11 15:01

I have a List of paths of files stored on my computer. My aim is to first filter out the files which have the same name and and then filter out those which have

3条回答
  •  抹茶落季
    2021-01-11 15:28

    Change your GetHashCode to work on the compared value. I.e. for your size comparer:

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

    And for the other:

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

    According to this answer - What's the role of GetHashCode in the IEqualityComparer in .NET?, the hash code is evaluated first. Equals is called in case of collision.

    Obviously it would be sensible to work on FileInfos, not on strings.

    So maybe:

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

    Of course, then you have to change your comparers to work on the correct type.

提交回复
热议问题