T实现IEquatable时如何比较2个List<T>?
How to compare 2 List<T> when T implements IEquatable?
我有一个 class 并实现了 IEquatable
:
public class MyObject: IEquatable<MyObject>
{
public string Name { get; set; }
public bool Equals(MyObject other)
{
if (other == null)
return false;
return this.Name.Equals(other.Name);
}
public override bool Equals(object o)
{
if (ReferenceEquals(null, o)) return false;
if (ReferenceEquals(this, o)) return true;
if (o.GetType() != GetType()) return false;
return Equals(o as MyObject);
}
public override int GetHashCode()
{
unchecked
{
int hash = 29;
hash = hash * 31 + Name != null ? Name.GetHashCode() : 0;
return hash;
}
}
}
为了使示例简短,我只保留了 Name
属性。 class 还有其他属性。
现在我有 MyObject
的 2 个列表(A,B),我想获得 A 中但 B 中缺少的项目的列表。
如何通过使用 LINQ(最好)并确保使用 IEquatable
(或使用 Equals)来做到这一点?
您可以使用 Enumerable.Except
,它会使用您的 IEquatable<MyObject>
:
IEnumerable<MyObject> missingInB = A.Except(B);
请注意,如果 Name
属性 在 GetHashCode
中用于标识对象,则它应该是只读的。
LINQ 方法将使用您覆盖的 Equals
和 GetHashCode
,通过实现 IEquatable<T>
或仅继承自 System.Object
。另一种选择:如果您不想修改 class.
,则传递自定义 IEqualityComparer<T>
to Except
(或其他 LINQ 方法)
我有一个 class 并实现了 IEquatable
:
public class MyObject: IEquatable<MyObject>
{
public string Name { get; set; }
public bool Equals(MyObject other)
{
if (other == null)
return false;
return this.Name.Equals(other.Name);
}
public override bool Equals(object o)
{
if (ReferenceEquals(null, o)) return false;
if (ReferenceEquals(this, o)) return true;
if (o.GetType() != GetType()) return false;
return Equals(o as MyObject);
}
public override int GetHashCode()
{
unchecked
{
int hash = 29;
hash = hash * 31 + Name != null ? Name.GetHashCode() : 0;
return hash;
}
}
}
为了使示例简短,我只保留了 Name
属性。 class 还有其他属性。
现在我有 MyObject
的 2 个列表(A,B),我想获得 A 中但 B 中缺少的项目的列表。
如何通过使用 LINQ(最好)并确保使用 IEquatable
(或使用 Equals)来做到这一点?
您可以使用 Enumerable.Except
,它会使用您的 IEquatable<MyObject>
:
IEnumerable<MyObject> missingInB = A.Except(B);
请注意,如果 Name
属性 在 GetHashCode
中用于标识对象,则它应该是只读的。
LINQ 方法将使用您覆盖的 Equals
和 GetHashCode
,通过实现 IEquatable<T>
或仅继承自 System.Object
。另一种选择:如果您不想修改 class.
IEqualityComparer<T>
to Except
(或其他 LINQ 方法)