C# Enumerable Sum(IEnumerable, Func)
Description
Computes the sum of the sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence.
Syntax
public static decimal Sum<TSource>(
this IEnumerable<TSource> source,
Func<TSource, decimal> selector
)
Parameters
TSource
- The type of the elements of source.source
- A sequence of values that are used to calculate a sum.selector
- A transform function to apply to each element.
Returns
returns The sum of the projected values.
Example
The following code example demonstrates how to use Sum to sum the projected values of a sequence.
/* w ww . j a va 2s. c om*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
List<Package> packages =
new List<Package>
{ new Package { Company = "A", Weight = 25.2 },
new Package { Company = "B", Weight = 18.7 },
new Package { Company = "C", Weight = 61.0 },
new Package { Company = "D", Weight = 33.8 } };
double totalWeight = packages.Sum(pkg => pkg.Weight);
Console.WriteLine("The total weight of the packages is: {0}", totalWeight);
}
}
class Package{
public string Company { get; set; }
public double Weight { get; set; }
}
The code above generates the following result.