问题描述
我要创建一个派生自列表类...
I'm creating a class that derives from List...
公共类MYLIST:列表< MyListItem> {}
我已经MyListItem ...
I've overridden Equals of MyListItem...
public override bool Equals(object obj)
{
MyListItem li = obj as MyListItem;
return (ID == li.ID); // ID is a property of MyListItem
}
我想有一个等于在MYLIST对象方法也将比较列表中的每个项目,调用equals()是每个MyListItem对象。
I would like to have an Equals method in the MyList object too which will compare each item in the list, calling Equals() on each MyListItem object.
这将是很好,只调用...
It would be nice to simply call...
MyList l1 = new MyList() { new MyListItem(1), new MyListItem(2) };
MyList l2 = new MyList() { new MyListItem(1), new MyListItem(2) };
if (l1 == l2)
{
...
}
...和具有由值完成的列表的比较。
...and have the comparisons of the list done by value.
什么是最好的办法...?
What's the best way...?
推荐答案
您可以使用 SequenceEqual 就行了LINQ的方法,因为你的列表实现IEnumerable。这将验证所有的元素都相同,并且以相同的顺序。如果顺序可以是不同的,则可以在第一列表排序。
You can use SequenceEqual linq method on the list since your list implements IEnumerable. This will verify all the elements are the same and in the same order. If the order may be different, you could sort the lists first.
这篇关于等于System.Collections.Generic.List&LT的方法; T> ...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!