Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何查找某一类型数组中的所有元素?_C#_Arrays_Findall - Fatal编程技术网

C# 如何查找某一类型数组中的所有元素?

C# 如何查找某一类型数组中的所有元素?,c#,arrays,findall,C#,Arrays,Findall,我以前从未使用过谓词,所以在使用Array.FindAll时遇到了很多问题 基本上,我有一个自己的自定义枚举数组,这里有公共枚举颜色{空、蓝、红、绿、紫、白、橙} 我的问题是我不明白如何使用FindAll来计算某个颜色在数组中出现的次数。我本来打算这样做的 Colors matches[]; matches = Array.FindAll(myArray,/*I don't know what to put here*/); int numOfMatches = matches.length;

我以前从未使用过谓词,所以在使用Array.FindAll时遇到了很多问题

基本上,我有一个自己的自定义枚举数组,这里有公共枚举颜色{空、蓝、红、绿、紫、白、橙}

我的问题是我不明白如何使用FindAll来计算某个颜色在数组中出现的次数。我本来打算这样做的

Colors matches[];
matches = Array.FindAll(myArray,/*I don't know what to put here*/);
int numOfMatches = matches.length;

例如,我应该使用什么作为第二个参数来查找蓝色之类的颜色?

您需要传递一个谓词。在本例中,您将检查给定的颜色是否与您感兴趣的颜色相同:

var matches = Array.FindAll(myArray, c => c == someColor);
您还可以使用
Enumerable.Count
方法来查找匹配数(如果以后不需要将它们用于其他任何事情):


您需要传递一个谓词。在本例中,您将检查给定的颜色是否与您感兴趣的颜色相同:

var matches = Array.FindAll(myArray, c => c == someColor);
您还可以使用
Enumerable.Count
方法来查找匹配数(如果以后不需要将它们用于其他任何事情):


您可以使用LINQ来实现这一点:

int numOfBlue = matches.Count(m => m == Colors.Blue);

它将只返回一个数字,而不是返回带有匹配元素的新数组。

您可以使用LINQ执行此操作:

int numOfBlue = matches.Count(m => m == Colors.Blue);
它将只返回一个数字,而不是返回带有匹配元素的新数组