简体   繁体   中英

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. The string is at itemarray[0] in dataList. 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:

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

Or you can do it using a combination of Except and Any :

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

In your example you are using an ArrayList . You should change this to List<object> or List<string> to use these methods. Otherwise you can write arrayList.Cast<object>() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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