无法让 Distinct 和 IEqualityComparer 在 ASP.net 6.1 中工作

Can't get Distinct and IEqualityComparer to work in ASP.net 6.1

我正在尝试删除电子邮件地址和 phone 号码匹配时的重复条目。我已经尝试了几种解决方案,但我什么都做不了。我什至尝试了下面发布的 link 中的 C# 示例。

https://msdn.microsoft.com/en-us/library/bb338049(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

似乎调用实际方法的行没有正常工作。在调试模式下,我希望程序在执行比较器时会慢一点。它似乎只是绕过比较器。这是我调用比较器的方式。

IEnumerable<MerchantConsumer> noduplicates = consumers2.Distinct(new MerchantConsumerComparer2());

我已将比较器代码添加到我的控制器中并在那里调用它。我还将比较器代码添加到实际实体 (MerchantConsumer class) 中并在那里调用它。

这是我的比较器代码。

 public class MerchantConsumerComparer2 : IEqualityComparer<MerchantConsumer>
    {
        // Products are equal if their names and product numbers are equal.
        public bool Equals(MerchantConsumer x, MerchantConsumer y)
        {

            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the products' properties are equal.
            return x.Email == y.Email && x.PhoneNumber == y.PhoneNumber;
        }

        // If Equals() returns true for a pair of objects 
        // then GetHashCode() must return the same value for these objects.

        public int GetHashCode(MerchantConsumer consumer)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(consumer, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashEmail = consumer.Email == null ? 0 : consumer.Email.GetHashCode();

            //Get hash code for the Code field.
            //int hashProductCode = product.Code.GetHashCode();
            int hashPhone = consumer.PhoneNumber == null ? 0 : consumer.PhoneNumber.GetHashCode();

            //Calculate the hash code for the product.
            return hashEmail ^ hashPhone;
        }

    }

这有效,但它不会删除重复的电子邮件。

var consumersFiltered = consumerList.GroupBy(i => i.PhoneNumber).Select(g => g.FirstOrDefault()).ToList();

是否有我需要研究的删除重复项的新方法?

非常感谢任何帮助。谢谢!

我实际上是通过将它转换为这样的列表来实现它的。在我看到的所有示例中,none 个都转换为列表。

var noduplicates = consumers2.Distinct(new MerchantConsumerComparer2()).ToList();

它看起来相当快,无论比较器是在 Controller 中还是在 Entity 中,它都能正常工作。