Posted by: Cirilo Meggiolaro | 11/11/2008

Tip of the day #28 – Sum method – Enumerable class – LINQ

The Sum method from Enumerable class under the System.Linq namespace is very straightforward to use.

The goal is to compute the sum of a sequence of numeric values.

How to…

The simplest way to use is:

int[] myArray1 = { 1, 5, 7, 10, 15, 16 };
int result = myArray1.Sum();

The Sum method has a large range of overloads for different numeric types and overloads that permit apply transformation for each item before add it to the sum.

Let’s imagine that we have an array that stores the unit price for each product in an order and we want to apply taxes for each item based on the value range. The code will be similar as the following:

// Array of unit prices for an order
decimal[] unitPrice = { 100.00M, 57.54M, 173.89M, 99.99M };

// Add the tax for each item before sum
decimal totalPrice = unitPrice.Sum(item => item > 100.00M ? item * 1.54M : item * 1.32M);

// totalPrice = 607.7302


Responses

  1. You convinced me that is time to study Linq…

    Thanks!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: