Search code examples
c#linq-to-objectsanonymous-methods

modify a variable in a anonymous method


I want to modify a local variable in a function of extension method. See

int myvar=0;
MyList.Where(
    x =>
        {
            if (condition)
                myvar += 1;
            return false;
        });
return myvar;

Why that is not working?


Solution

  • You really don't want to modify a local variable in the body of a Where predicate. Functions with side-effects like this are bad news; try to imagine what would happen if this comes (for example) from a parallel enumerable generated by AsParallel() - you'll have a race condition.

    If you explain what you're trying to accomplish, I'm sure that one of us could provide a better means to that end. My guess is that it would look something like this:

    int count = myList.Count(x => condition(x));