views:

45

answers:

2

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?

+6  A: 

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));
Aaronaught
Now i use .Count() method but my list is very huge and for performance reasons i don't want to use that.
Navid Farhadi
@Navid: Switching to a method like the one in the question isn't going to improve anything, performance-wise; no matter what, the sequence needs to be iterated entirely and each item evaluated. The only reason this version runs faster is because `Where` uses deferred execution and in this case is never executed because you never iterate the list.
Aaronaught
So what can i do?
Navid Farhadi
@Navid: That depends. What is your goal? Where does the data come from? Why is the list so big?
Aaronaught
In fact i write a program that use evolutionary algorithm to solve a problem. In calculate fitness i use linq to object and this code runs so many that leads to low speed of my program. (i use profiler to know this)
Navid Farhadi
this is a part of my fitness function : fitness += GeneList.Where( x => (x as Gene).Group.Features.Except((x as Gene).Classroom.Features).Count() == 0).Count() * _weights[3];
Navid Farhadi
@Navid, that's not a whole lot of context, but offhand I can tell you that the `(...).Count() == 0` part is highly inefficient and could be replaced by an `!(...).Any()`.
Aaronaught
Thanks very much.
Navid Farhadi
A: 

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

Marcelo Cantos