IEqualityComparer<T> 不适用于 List<T>.Distinct() 方法

IEqualityComparer<T> does not work with List<T>.Distinct() method

我有以下简单对象:

public class Net : IEqualityComparer<Net>
{
    public string Name { get; private set; }
    public int Id { get; set; }

    private Gate _inGate;
    private Gate _outGate;
    private NetValue _value = NetValue.NotSet;
    private bool _isMiddleNet;

    //constructor and stuff!!!.....

    //Equality comparer
    public bool Equals(Net x, Net y)
    {
        return (x.Id == y.Id && x.Name == y.Name);
    }

    public int GetHashCode(Net obj)
    {
        return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
    }

    public override int GetHashCode()
    {
        return 13 * Id.GetHashCode() + 7 * Name.GetHashCode();
    }

所以基本上我有兴趣说这个对象的 2 个实例是相等的当且仅当它们的 IdName 成员是相等的...

但是在另一个 class 的其他地方我必须 List<Net> 并且我想对这些列表进行区分:

    inputNetsA = inputNetsA.Distinct().ToList();
    inputNetsB = inputNetsB.Distinct().ToList();

但这根本行不通!我做错了什么?

您需要创建对象 IEquatable<T>. The IEqualityComparer<T> 是一个对象接口,用于将两个对象相互比较。 IEquatable<T> 用于比较一个对象与另一个相同类型的对象。

否则,如果您想使用 IEqualityComparer<T>,它意味着要传递给 Distinct() 方法。

// better to extend off of EqualityComparer<T> instead of
//     implementing IEqualityComparer<T> directly
public class NetComparer : EqualityComparer<Net>
{
    public override bool Equals(Net x, Net y)
    {
        return (x.Id == y.Id && x.Name == y.Name);
    }

    public override int GetHashCode(Net obj)
    {
        return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
    }
}

inputNetsA = inputNetsA.Distinct(new NetComparer()).ToList();