简体   繁体   中英

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?

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

Where方法返回一个IEnumerable<T>但实际上并没有进行枚举(使用foreach或通过手动迭代生成的IEnumerator<T> )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM