You can always do:
var sum = this.Chances.Sum(c => c.Value);
This is shorter and clearer coder. However, performance wise, the foreach
might be just as fast or even faster.
Note, however, that the implementation of Sum
uses checked mode, which can also affect the performance, so if your code is that critical, the foreach
will be definitely faster.
However, we are talking about very fast code either way, if Chance
is something like
class Chance {
public long Value {get; set;}
}
and we have a list of 10 million items
var chances = Enumerable.Range(0, 10000000).Select(i => new Chance{Value = i});
on my machine, I'm getting 780ms for the foreach
, and 1030ms for the Sum
. So if your code goes nowhere near the million range, you're set with the Sum, as the code is way more obvious.
I.e. since your method is named CountChances
, there's a chance that a support developer might mistake it's functioning, as it is not obvious at a glance that it actually sums the chances. No such chance with the Sum
method.