user1527762
user1527762

Reputation: 957

Count of matching elements in a list and array

I have a list and an array. I want to find out the number/count of elements in the array that match those in the list

List<int> list = new List<int>{ 1, 2, 3, 4 };

int[] array = new int[] { 1, 2 };

Since the two matching elements are 1 and 2, I am expecting a result of count 2. Can someone please point me in the right direction?

Upvotes: 1

Views: 3077

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564851

You can use:

int matches = list.Intersect(array).Count();

Note that this will only work if the list and array only contain unique values.

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 149068

You can use a little Linq with the Count extension method:

var count = array.Count(list.Contains);

Or if you know that there are no duplicate values in the the array, you can use the Intersect method:

var count = array.Intersect(list).Count();

Upvotes: 4

Related Questions