Thursday, October 13, 2011

Reverse words in a string using Aggregate function in LINQ

Aggregate is a cool function in LINQ that applies a function over a sequence.

Aggregate(TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> function)

That applies a function that takes a seed value to initialize the result and the next item in a sequence and returns a result. the second parameter is the delegate we pass that will be done on the sequence that takes a current total and the next value, and returns the new total. this works recursively for all the items in a sequence.
string str = "this is a sentence";
string result = str.Split(' ').Aggregate("", (total, next) => next + " " + total);
//result : sentence a is this


Post a Comment