IEqualityComparer not working as intended

后端 未结 3 1857
梦毁少年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:17

    Your GetHashCode must return the same value for any objects that are of equal value:

    // Try this
    public int GetHashCode(string obj)
    {
        return Path.GetFileName(x).GetHashCode();
    }
    
    // And this
    public int GetHashCode(string obj)
    {
        return new FileInfo(x).Length.GetHashCode();
    }
    

    But this is a much easier way for the whole problem without the extra classes:

    var query = FilesList
                    .GroupBy(f => Path.GetFileName(f)).Select(g => g.First())
                    .GroupBy(f => new FileInfo(f).Length).Select(g => g.First())
                    .ToList();
    

提交回复
热议问题