Reputation: 3467
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
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
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