Reputation: 1557
I simply want to add up values from a specific list of custom objects I am currently doing it like this:
private int CountChances()
{
int totalChance = 0;
foreach(var chance in this.Chances)
{
totalChance += chance.Value;
}
return totalChance;
}
Is there a way to do this faster without the foreach loop? I'm almost certain linq should be able to do this quickly but I cannot seem to find how to do it.
Upvotes: 0
Views: 105
Reputation: 30902
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.
Upvotes: 7
Reputation: 3114
You can do that like this:
this.Chances.Sum(e => e.Value);
Just include:
using System.Linq;
Upvotes: 5