LINQ Distinct not using the IEqualityComparer?

本文关键字:IEqualityComparer the using Distinct not LINQ | 更新日期: 2023-09-27 17:59:38

我有以下模型:

public class Word {
      public string Original { get; set; }
      public string Normalized { get; set; }
      public string Root { get; set; }
      public string Subroot { get; set; }
      public Regex SubrootRegex { get; set; }
}

我创建了以下三个IEqualityComparer<Word>:

public class NormalizedWordComparer : IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Normalized == y.Normalized;
     }
     public int GetHashCode(Word obj) {
          return obj.GetHashCode();
     }
}
public class RootWordComparer : IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Root == y.Root;
     }
     public int GetHashCode(Word obj) {
          return obj.GetHashCode();
     }
}
public class SubrootWordComparer : IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Subroot == y.Subroot;
     }
     public int GetHashCode(Word obj) {
          return obj.GetHashCode();
     }
}

在另一节课上,我试图做以下事情:

_normalizedWords = ConfigurationFacade.Words.Select(w => {
     Word word = new Word() { Original = w };
     word.Normalized = Normalize(word, _filters);
     word.Root = GetRoot(word.Normalized, ConfigurationFacade.WordRootPercentage);
     word.Subroot = GetRoot(word.Root, ConfigurationFacade.WordSubrootPercentage);
     word.SubrootRegex = null; //Complicated regex here
     return word;
}).Distinct(new NormalizedWordComparer());
_wordRoots = _normalizedWords.Distinct(new RootWordComparer());
_wordSubroots = _wordRoots.Distinct(new SubrootWordComparer());

然而,_normalizedWords_wordRoots_wordSubroots最终都具有相同数量的元素,就好像Distinct()方法不起作用或比较器被忽略一样。

我用调试器检查了这些元素,有很多元素具有相同的Root值,所以_wordRoots中应该只有一个,但事实并非如此,它们没有被删除或过滤。

为什么我的Distinct()不工作?

LINQ Distinct not using the IEqualityComparer?

为什么我的Distinct()不起作用?

因为Distinct首先检查哈希代码(因为这是一个快速检查,查看两个对象是否可以相等),然后调用Equals。由于您的GetHashCode实现都是相同的(并且与Equals方法不对应),因此Distinct并不像您预期的那样工作。

更改您的GetHashCode方法以符合Equals:

public class NormalizedWordComparer : IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Normalized == y.Normalized;
     }
     public int GetHashCode(Word obj) {
          return obj.Normalized.GetHashCode();
     }
}
public class RootWordComparer: IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Root == y.Root;
     }
     public int GetHashCode(Word obj) {
          return obj.Root.GetHashCode();
     }
}
public class SubrootWordComparer : IEqualityComparer<Word> {
     public bool Equals(Word x, Word y) {
          return x.Subroot == y.Subroot;
     }
     public int GetHashCode(Word obj) {
          return obj.Subroot.GetHashCode();
     }
}
相关文章:
  • 没有找到相关文章