0

I have a Class MyClass that have a method MyFunction which return a Boolean. then I have a array MyArray of MyClass and I need to return true if this array have a object where MyFunction returns true, i actually use this:

 bool MyOtherFunction () {
     foreach (MyClass x in MyArray.Where(y => y.MyFunction))
        {
            return true;
        }
     return false;
 }

But Visual Studio keeps warning me because "Local variable 'x' is never used", So, how can I check this without declaring a new variable?

1
  • Did you want to use an if rather than a foreach loop? Commented Jan 24, 2016 at 3:36

1 Answer 1

3

You can replace the entire body of your function with

return MyArray.Any(x => x.MyFunction());

Your current function is essentially filtering out any results that do not return true from the call to MyFunction. If there are results, you'll begin enumerating the result of your Where filter, and at the first item return true. If there are no results, there will be nothing to enumerate, and you will return false. By using LINQ's Any method, you will instead enumerate until one of the item's in the array's MyFunction call returns true, at which point you will have met your condition and can return true. If MyFunction is a potentially expensive call this will be much quicker than executing the function for every possible element in your array when all you really want is to return if any one happens to be true. Of course, if it is expensive, you're going to be stuck executing it for every element if they all return false.

Sign up to request clarification or add additional context in comments.

2 Comments

The answer is correct, the explanation (how Where works) isn't. Where (like most of LINQ) is just as lazy as Any. So MyFunction will not be called more than absolutely necessary either way. In other words, both method bodies work the way you explained Any.
You're right, it would exit out because the return ends execution, thanks for pointing that out.

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.