I have the following code
int someCount = 0;
for ( int i =0 ; i < intarr.Length;i++ )
{
if ( intarr[i] % 2 == 0 )
{
someCount++;
continue;
}
// Some other logic for those not satisfying the condition
}
Is it possible to use any of the Array.Where or Array.SkiplWhile to achieve the same?
foreach(int i in intarr.where(<<condtion>> + increment for failures) )
{
// Some other logic for those not satisfying the condition
}
Nothing (much) prevents you from rolling your own
Wherethat counts the failures. “Nothing much” because neither lambdas nor methods withyield returnstatements are allowed to reference out/ref parameters, so the desired extension with the following signature won’t work:However, we can declare a local variable for the failure-count and return a
Func<int>that can get the failure-count, and a local variable is completely valid to reference from lambdas. Thus, here’s a possible (tested) implementation:…and here’s some test code that exercises it:
The above test, when run outputs:
There are a couple caveats I feel obligated to warn about. Since you could break out of the loop prematurely without having walked the entire
IEnumerable<>, the failure-count would only reflect encountered-failures, not the total number of failures as in @nneonneo’s solution (which I prefer.) Also, if the implementation of LINQ’sWhereextension were to change in a way that called the predicate more than once per item, then the failure count would be incorrect. One more point of interest is that, from within your loop body you should be able to make calls to the getFailureCount Func to get the current running failure count so-far.I presented this solution to show that we are not locked-into the existing prepackaged solutions. The language and framework provides us with lots of opportunities to extend it to suit our needs.