Posted by: Cirilo Meggiolaro | 11/10/2008

Tip of the day #27 – Aggregate method – Enumerable class – LINQ

The Aggregate method from Enumerable class under the System.Linq namespace can help you to apply accumulator functions for each item in a collection using anonymous methods.

A string concatenation example

Let’s use the following array:

string[] myArray1 = { “100”, “Some Street”, “Suite 200”, “New York” };

You may want to concatenate all the items in the previous array. You can use the aggregate method to perform that:

string myResult = myArray1.Aggregate((currentItem, nextItem) => currentItem + ” “ + nextItem);

// myResult = “100 Some Street Suite 200 New York”

A numeric calculation example

Let’s use numeric types to calculate the product of a multiplication between an item and its next item in the following array:

int[] myArray1 = { 1, 5, 7, 10, 15, 16 };

You could use a loop to perform the calculation or use the Aggregate method.

int sumResults = 1;

foreach (int item in myArray1)
{
sumResults *= item;
}

// 84000

The loop above can be replaced by the following call to Aggregate method:

sumResults = myArray1.Aggregate((currentItem, nextItem) => currentItem * nextItem); // 84000


Advertisements

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: