问题
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