grady
grady

Reputation: 12785

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 :-)

Upvotes: 2

Views: 1315

Answers (1)

Mark Byers
Mark Byers

Reputation: 839214

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));

Upvotes: 4

Related Questions