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

### Like this:

Like Loading...

*Related*

You convinced me that is time to study Linq…

Thanks!

By:

Fadachion 11/11/2008at 7:29 am