How to pass each value of array to method using linq
Let say I have an array:
string[] s = GetAr开发者_Python百科ray();
and method:
public bool CheckIfInArray() { .. }
I want to pass each value of that array in to the method and get a bool result as soon as there are any first matching (after first matching there no reason to loop to the last element of array ).
Kind of like this:
s.ContainsAtLeasFirstMatching(x => CheckIfInArray(x))
I don't want to use loops. Is it possible to achieve this with LINQ?
I presume the signature of the method is actually:
public bool CheckIfInArray(string str) { .. }
In that case, you can write:
string[] s = GetArray();
bool atLeastOneMatch = s.Any(CheckIfInArray);
If you are interested in using the first matched element, you can also use FirstOrDefault
:
// firstMatch will be null if there is no match
string firstMatch = s.FirstOrDefault(CheckIfInArray);
You can do this with the Any() method.
s.Any(x => CheckIfInArray(x))
You may want to take a look at the Enumerable Methods MSDN page to see wich methods are available to you and what they are used for.
精彩评论