等于System.Collections.Generic.List&LT的方法; T> ...? [英] Equals method of System.Collections.Generic.List<T>...?

查看:158
本文介绍了等于System.Collections.Generic.List&LT的方法; T> ...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个派生自列表类...

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> ...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆