perivam : Vamsi's Writings

The power of LINQ : The Aggregate method

LINQ never ceases to amaze me. Recently, while working on a problem in the Google CodeJam, I realised that using LINQ can reduce code and make your code look clean, compact and elegant. So here’s showcasing the LINQ extension method that made my day – Aggregate. Here are three interesting uses of the Aggregate method that I could think of which makes writing the usual for loops so C# 2.0 (or 2006, whichever you prefer).

The first example is what I actually used to solve one of the CodeJam problems. The second example is one of my interview screener questions, reversing the words in a sentence. The third example materialized when I realized that the process of converting a binary number to base 10 fits very well in the aggregation logic.

Leave a Reply