C# Enumerable Sum(IEnumerable, Func>)
Description
Computes the sum of the sequence of nullable Int64 values that are obtained by invoking a transform function on each element of the input sequence.
Syntax
public static Nullable<long> Sum<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Nullable<long>> 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.
Example
using System;/* w ww . java2s . co m*/
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 },
new Package { Company = "B", Weight = 18 },
new Package { Company = "C", Weight = 61 },
new Package { Company = "D", Weight = 33 } };
Console.WriteLine("The total weight of the packages is: {0}", packages.Sum(pkg => pkg.Weight));
}
}
class Package
{
public string Company { get; set; }
public long? Weight { get; set; }
}
The code above generates the following result.