简体   繁体   English

列表和数组中匹配元素的计数

[英]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? 由于两个匹配元素分别为1和2,因此我希望得到2的结果。有人可以指出正确的方向吗?

You can use a little Linq with the Count extension method: 您可以在Count扩展方法中使用一点Linq:

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: 或者,如果您知道数组中没有重复的值,则可以使用Intersect方法:

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

You can use: 您可以使用:

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

Note that this will only work if the list and array only contain unique values. 请注意,这仅在列表和数组仅包含唯一值时才有效。

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

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