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

时间:2015-06-30 04:03:32

标签: c# .net linq iequalitycomparer

我有以下简单的对象:

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成员相等...

但在另一个班级的其他地方,我必须List<Net>,我想在这些名单上进行区分:

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

但这不会有效!我做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要制作对象IEquatable<T>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();