0

Let say I have an array:

string[] s = GetArray();

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?

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

why not s.Any(CheckIfInArray)?
@Andrey, you could do it that way as well due to the magic of inference. In general I've found that being explicit helps most other developers understand what exactly is going on when using inline delegates, especially in extension methods.
no magic here, they have same signature. Well, I pity those developers that use lambdas and don't know basics of delegates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.