简体   繁体   English

将一个集合中的所有项目与另一个集合中的项目进行比较?

[英]Compare all items from a Collection with items from another Collection?

Hey, I have this code here: 嘿,我在这里有以下代码:

ArrayList arrayList = new ArrayList();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");

List<DataRow> dataList = GetDataList(some params);

Now I want to check if arrayList contains ther elements from dataList. 现在,我要检查arrayList是否包含dataList中的ther元素。 The string is at itemarray[0] in dataList. 字符串位于dataList中的itemarray [0]处。 Is there a nice short code version to do that? 有一个不错的短代码版本可以做到这一点吗?

Thanks :-) 谢谢 :-)

In .NET 3.5 to check if all the elements from one list are contained in another list: 在.NET 3.5中,检查一个列表中的所有元素是否包含在另一列表中:

bool result = list.All(x => dataList.Contains(x));

Or you can do it using a combination of Except and Any : 或者您可以结合使用ExceptAny来做到这一点:

bool result = !list.Except(dataList).Any();

In your example you are using an ArrayList . 在您的示例中,您正在使用ArrayList You should change this to List<object> or List<string> to use these methods. 您应该将其更改为List<object>List<string>以使用这些方法。 Otherwise you can write arrayList.Cast<object>() . 否则,您可以编写arrayList.Cast<object>()

bool result = arrayList.Cast<object>().All(x => dataList.Contains(x));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM