The Ascending Iterator

  • My Github repos
  • My LinkedIn profile
  • My Facebook profile
  • E-Mail me

Programming

  • In the memory of an Icon
  • Telescopic text
  • Remember, ActionScript is ECMAScript
  • Hiring is a first class responsibility
  • The power of LINQ : The Aggregate method
  • Legacy applications and Age of Empires

Mathematics

  • Gödel, Escher, Bach, Me and Reddit

I Learnt Something Today

  • ASP.NET Session State gotcha

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.

// Aggregate works on any IEnumerable<T> collection
IEnumerable<int> collection = new int[5] {1, 2, 3, 4, 5};

// Example 1: XOR all the integers in the collection.
int xorResult =
  collection.Aggregate(
    (runningResult, next) => runningResult ^ next);

// Example 2: Reverse words in a sentence
string[] words = "that's what she said".Split(' ');
// Observe the way we are concatenating the strings
string reversed =
  words.Aggregate(
    (sentence, next) => next + " " + sentence);

// Example 3: Convert base 2 int to base 10 int
int[] base2 = new int[] { 1, 1, 1, 0, 0 };
int base10 =
  base2.Aggregate(0, (result, next) => 2 * result + next);

view raw Aggregate.cs This Gist brought to you by GitHub.