0

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?

Navid Farhadi
  • 3,397
  • 2
  • 28
  • 34

2 Answers2

6

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
  • 120,909
  • 25
  • 266
  • 342
  • Now i use .Count() method but my list is very huge and for performance reasons i don't want to use that. – Navid Farhadi Apr 28 '10 at 13:56
  • 1
    @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 Apr 28 '10 at 13:57
  • @Navid: That depends. What is your goal? Where does the data come from? Why is the list so big? – Aaronaught Apr 28 '10 at 14:03
  • 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 Apr 28 '10 at 14:06
  • 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 Apr 28 '10 at 14:08
  • @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 Apr 28 '10 at 14:22
0

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
  • 181,030
  • 38
  • 327
  • 365