Steve Smith's Blog

Musings on Software and the Developer Community

Use LINQ Aggregate to Multiply a Series of Digits

The LINQ Aggregate() extension method uses a Func<int, int, int> to operate on items in a series.  If you want to use it, for example, to return the product of each value with its successor, you can do something like this:

Func<int, int, int> producter = (one, two) => one * two;
var result = subString.ToCharArray().ToDigits().Aggregate(producter);

Of course, you don’t need the intermediate value.  You can simply use a lambda directly for the Aggregate()’s parameter:

//Func<int, int, int> producter = (one, two) => one * two;
var result = subString.ToCharArray().ToDigits().Aggregate((p1,p2) => p1 * p2);

With a loop to keep track of the largest result returned for a substring of length 5, you can easily use this technique to solve Euler 8.

    kick it on DotNetKicks.com

Sunday, 06 September 2009

Comments

 avatar

MIke said on 06 Sep 2009 at 8:03 AM

I've found it useful for putting together comma separated lists as well.

var items = new string[] {"1", "2", "3"};

var csl = items.Aggregate((s1,s2) => s1 + "," + s2);


 avatar

UGG Boots sale said on 28 Jan 2010 at 2:28 AM

var items = new string[] {"1", "2", "3"};

var csl = items.Aggregate((s1,s2) => s1 + "," + s2);


 avatar

Life Insurance Quotes said on 02 Feb 2010 at 1:51 AM

including a Primes generator for previous Euler problems, the base case given in the problem can be reduced to this NUnit test:


Leave a Comment

Please join the discussion and share your thoughts.