6
\$\begingroup\$

Is there a tighter way to write this code?

foreach(var processName in processNames)
{
    bool launched = launch(processName);
    if (!launched)
    {
        return false;
    }
}
return true;

I'm not sure what this kind of approach is called. But basically if any false the whole thing is false, otherwise it's true. The closest I can get is:

return !processNames.Any(process => !launch(process));

but I think the first approach is better because it's easier to understand.

\$\endgroup\$
5
\$\begingroup\$

Usually positive conditions are much easier to understand than negative ones and even easier then two negatives in the same expression. You can flip it and get rid of both negations by using All instead:

return processNames.All(process => launch(process));

Now that the nagations are gone you can further shorten this by removing the lambda:

return processNames.All(launch);

This is possible because the launch method signature matches the delegate Func<string, bool> required by All.

\$\endgroup\$
  • \$\begingroup\$ geez, that is the perfect answer. I don't think I knew there was a .All. Thanks. \$\endgroup\$ – user875234 Dec 22 '17 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.