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
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:
or