This is a mirror of official site: http://jasper-net.blogspot.com/

C#/.NET Little Wonders: Five Easy Sequence Aggregators

| Sunday, August 28, 2011
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders post can be found here.

Today we will look at five easy ways to aggregate sequences.  Often times when we’re looking at a sequence of objects, we want to do perform some sort of aggregation across those sequences to find a calculated result from the sequence.

The methods we will be looking at are LINQ extension methods from the Enumerable static class which do just that.  Like most of the LINQ extension methods discussed before, these operate on IEnumerable<TSource> sequences.
Sum() – calculate the total value across sequence

So, as you’d expect, the Sum() method in the Enumerable static class is useful for computing the total of values in a sequence.  This can be done in one of two ways depending on the form of the extension method invoked (of course, ignoring the implicit source parameter):

    Sum()
        Sums the values of the sequence.
        Source type must be one of the following types: int, long, single, double, decimal or a Nullable wrapped variant.
    Sum(Func<TSource, X> projection)
        Sums the results of a projection on items in the sequence.
        Technically, X must be one of the following types: int, long, single, double, decimal or Nullable wrapped variant.
        However, if the projection is a lambda or anonymous delegate it can infer int from narrower numeric types.

Notice a few things here.  First of all, even though many types in C# support addition, the Sum() method – no projection - only supports int, long, single, double, and decimal. 

// works for any sequences of allowed numeric types
double[] data = { 3.14, 2.72, 1.99, 2.32 };
var result = data.Sum();

// does NOT work for sequences of disallowed numeric types
short[] shortData = { 1, 2, 5, 7 };

// Compiler ERROR: no form of Sum() exists for short, uint, etc
var shortResult = shortData.Sum();


Read more: James Michael Hare
QR: c.net-little-wonders-five-easy-sequence-aggregators.aspx

Posted via email from Jasper-net

0 comments: