使用默认平等比较器对Linq Group进行关键比较

我正在尝试使用显式键类型对某些对象执行一个Linq GroupBy.我没有将IEqualityComparer传递给GroupBy,所以根据文档:

The default equality comparer Default is used to compare keys.

它解释了EqualityComparer< T>.默认属性如下所示:

The Default property checks whether
type T implements the
System.IEquatable<T> generic interface
and if so returns an
EqualityComparer<T> that uses that
implementation.

在下面的代码中,我将一组Fred对象分组.它们具有称为FredKey的键类型,其实现IEquatable< FredKey&gt ;. 这应该足以使分组工作,但分组不起作用.在下面的最后一行我应该有2组,但是我没有,我只有3组包含3个输入项. 为什么分组不起作用?

class Fred
{
    public string A;
    public string B;
    public FredKey Key
    {
        get { return new FredKey() { A = this.A }; }
    }
}

class FredKey : IEquatable<FredKey>
{
    public string A;
    public bool Equals(FredKey other)
    {
        return A == other.A;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var f = new Fred[]
        {
            new Fred {A = "hello", B = "frog"},
            new Fred {A = "jim", B = "jog"},
            new Fred {A = "hello", B = "bog"},
        };

        var groups = f.GroupBy(x => x.Key);
        Debug.Assert(groups.Count() == 2);  // <--- fails
    }
}
最佳答案
MSDN

If you implement IEquatable, you should also override the base class implementations of Object::Equals(Object) and GetHashCode() so that their behavior is consistent with that of the IEquatable::Equals method. If you do override Object::Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals() method return consistent results.

添加到FredKey,它应该工作

public override int GetHashCode()
    {
        return A.GetHashCode();
    }

转载注明原文:使用默认平等比较器对Linq Group进行关键比较 - 代码日志