简体   繁体   English

如何在某种类型的数组中找到所有元素?

[英]How do I find all elements in an array of a certain type?

I've never worked with predicates before so I'm having a lot of trouble using Array.FindAll 我以前从未使用过谓词,因此在使用Array.FindAll时遇到了很多麻烦

Basically I have an array of my own custom enum here public enum Colors { Empty, Blue, Red, Green, Purple, White, Orange }; 基本上,我在这里有一个自己的自定义枚举数组。public enum Colors {空,蓝色,红色,绿色,紫色,白色,橙色};

My issue is I don't understand how to use FindAll to count the number of times a certain color occurs in the array. 我的问题是我不明白如何使用FindAll来计算数组中某种颜色出现的次数。 I was going to do something like this... 我打算做这样的事情...

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

What do I use as the second paramater to find a color like Blue for example? 例如,我如何将第二个参数用作查找像蓝色这样的颜色?

You need to pass a predicate. 您需要传递一个谓词。 In this case, you would check to see if the given color was equal to the one you are interested in: 在这种情况下,您将检查给定的颜色是否等于您感兴趣的颜色:

var matches = Array.FindAll(myArray, c => c == someColor);

You could also use the Enumerable.Count method to find the number of matches (if you don't need to use them for anything else afterward): 您还可以使用Enumerable.Count方法查找匹配项的数量(如果以后不需要将其用于其他任何事情):

var numOfMatches = myArray.Count(c => c == someColor);

You can use LINQ to do that: 您可以使用LINQ来做到这一点:

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

It will return just a number, instead of returning new array with matching elements. 它只会返回一个数字,而不是返回带有匹配元素的新数组。

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

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