Navid Farhadi
Navid Farhadi

Reputation: 3467

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?

Upvotes: 0

Views: 128

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185970

The Where method returns an IEnumerable<T> but you haven't actually enumerated it (with foreach, or by manual iteration over the resulting IEnumerator<T>).

Upvotes: 0

Aaronaught
Aaronaught

Reputation: 122664

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));

Upvotes: 6

Related Questions