C# Select query not modifying external variable

梦想与她 提交于 2021-02-07 09:34:51

问题


I have a class with n elements, and a property that returns the root sum square of the elements:

public double Length 
{ 
    get 
    { 
        double sum = 0.0; 
        Elements.Select(t => sum += t * t);  
        return Math.Sqrt(sum); 
    } 
}

However, that doesn't work - no matter the value of the elements, sum remains 0.0.
Why doesn't this work?

Note: I have already implemented it another way, but am looking to understand why the above code does not work


回答1:


LINQ uses deferred execution – the Select Method doesn't execute the lambda for all elements immediately, but returns an IEnumerable<T> which, when executed, performes the lambda on each element as it's enumerated.

Also note that LINQ is for querying, not for executing a block of code for each element. You should write your code such that there is no statement in the lambda, only a expression that is free of side-effects. You can use the Sum Method when you're trying to calculate a sum:

public double Length 
{ 
    get 
    { 
        double sum = elements.Select(t => t * t).Sum();
        return Math.Sqrt(sum); 
    } 
}

or

public double Length 
{ 
    get 
    { 
        double sum = elements.Sum(t => t * t);
        return Math.Sqrt(sum); 
    } 
}



回答2:


Deferred execution.

Try this:

public double Length
{
    get { return Math.Sqrt(Elements.Sum(t => t * t)); }
}

Here the linq query is executed immediately.




回答3:


This don't work because Deferred Execution. You can read this

LINQ and Deferred Execution

Understanding LINQ's Deferred Execution



来源:https://stackoverflow.com/questions/11287070/c-sharp-select-query-not-modifying-external-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!