私はList<CustomObject>
を持っており、重複を削除したいと考えています。
2つのカスタムオブジェクトの値がproperty: City
の場合、それらを重複して呼び出します。
私はIEquatableを次のように実装しましたが、リストから重複を取り除くことはできません。リストからの重複を避けるためにIEquatable <T>を実装する<T>
何が欠けていますか?
public class CustomAddress : IAddress, IEqualityComparer<IAddress>
{
//Other class members go here
//IEqualityComparer members
public bool Equals(IAddress x, IAddress y)
{
// Check whether the compared objects reference the same data.
if (ReferenceEquals(x, y)) return true;
// Check whether any of the compared objects is null.
if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
return false;
// Check whether the Objects' properties are equal.
return x.City.Equals(y.City);
}
public int GetHashCode(IAddress obj)
{
// Check whether the object is null.
if (ReferenceEquals(obj, null)) return 0;
int hashAreaName = City == null ? 0 : City.GetHashCode();
return hashAreaName;
}
}
私はあなたが比較演算を必要とするだけで、特定のプロパティの重複を一致させるには、.NET 3.5
LinqのDistinct()拡張メソッドを使用します。 –