您必須重寫Equals
和GetHashCode
有意義。您也可以實現IEquatable<Obj>
或使用LINQ方法(如SequenceEqual
或Except
)的自定義IEqualityComparer<Obj>
。例如:
public class Obj: IEquatable<Obj>
{
public List<X> xlist;
public List<Y> Ylist;
public bool mybool;
public bool Equals(Obj other)
{
if (other == null) return false;
if(object.ReferenceEquals(this, other)) return true;
if (mybool != other.mybool) return false;
return xlist.SequenceEqual(other.xlist) && Ylist.SequenceEqual(other.Ylist);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
unchecked
{
int hash = mybool ? 13 : 19;
foreach (X x in xlist)
{
hash = hash * 31 + x.GetHashCode();
}
foreach (Y y in Ylist)
{
hash = hash * 31 + y.GetHashCode();
}
return hash;
}
}
}
public class X: IEquatable<X>
{
public int x;
public float y;
public bool Equals(X other)
{
if (other == null) return false;
if (object.ReferenceEquals(this, other)) return true;
return x == other.x && y == other.y;
}
public override bool Equals(object obj)
{
var other = obj as X;
if (other == null) return false;
return this.Equals(other);
}
public override int GetHashCode()
{
unchecked
{
int hash = 19;
hash = hash * 31 + x;
hash = hash * 31 + (int)y;
return hash;
}
}
}
public class Y : IEquatable<Y>
{
public string str;
public bool y;
public bool Equals(Y other)
{
if (other == null) return false;
if (object.ReferenceEquals(this, other)) return true;
return str == other.str && y == other.y;
}
public override bool Equals(object obj)
{
var other = obj as Y;
if (other == null) return false;
return this.Equals(other);
}
public override int GetHashCode()
{
unchecked
{
int hash = 19;
hash = hash * 31 + (str == null ? 0 : str.GetHashCode());
hash = hash * 31 + (y ? 1 : 0);
return hash;
}
}
}
現在你可以使用SequenceEqual
您List<Obj>
:
bool sameItemsSameOrder = list1.SequenceEqual(list2); // finally you got your one-liner
你想知道'list1'中的所有'xlist'項是否等於'list2'中的所有'xlist'項和'Ylist'中的相同嗎?或者你也想要主持'Obj'本身。但是,訂單是否重要? –
只是我的看法,但不要如此癡迷LINQ。 LINQ存在爲您節省時間。如果您花時間瞭解如何編寫LINQ查詢的時間比編寫等效循環所用的時間要長,那麼您應該只編寫循環。 – Taekahn