Here is a link to a explanation of the linq aggregate method on Det Net Tutorials: LINQ Aggregate Method in C# The most powerful form allows you to set a seed value to start the Aggregate computation and a result selector to perform a final calculation at the end calculation. I like the way the examples are written in the examples, it makes it so much easier to see what is being done.
List ints = [4, 6, 9, 1, 3, 5];
List decimals = [4.2m, 6.3m, 9.7m, 1.8m, 3.4m, 5.1m];
// Aggregate to (total revenue, count), then project to average
decimal averageDecimals = decimals.Aggregate(
seed: (Total: 0m, Count: 0),
func: (acc, s) => (acc.Total + s, acc.Count + 1),
resultSelector: acc => acc.Count > 0 ? acc.Total / acc.Count : 0m);
decimal averageInts = ints.Aggregate(
seed: (Total: 0m, Count: 0),
func: (acc, s) => (acc.Total + (decimal)s, acc.Count + 1),
resultSelector: acc => acc.Count > 0m ? acc.Total / (decimal)acc.Count : 0m);
Console.WriteLine($"Average Decimals: ${averageDecimals:F2}");
Console.WriteLine($"Average Ints: ${averageInts:F2}");
I know their are already methods for calculating an average, it is just a good example to see how the Aggregate method is used
No comments:
Post a Comment