Getting Sneaky with LINQ’s Aggregate Function

My favourite programming aide

Here’s a really crafty use of the .Aggregate function of C#’s LINQ.

x = IQueryableOfSomething.Select(n => n.ToString()).Aggregate((p, q) => p + ", " + q));

It produces a comma separated list of the items in IQueryableOfSomething. So if it were a list of colours one might get:

Red, Green, Orange, Blue

The cunning thing about it is that there are only separators between the items, there isn’t an extra one at the end. Coping with this in inline code  always makes it look pants. This is much cooler.


Having initially posted this an “anonymous coward” pointed out that in the initial case one can use String.Join. This is true but my point really wasn’t specific to this instance. The idea was to start thinking outside the bounds of the normal boring aggregate operations. It’s a much more useful feature than just sums and averages. e.g.

byte csum = EncodedMessage.Aggregate((x, y) => (byte)(x ^ y));

What does this do? It creates a one byte checksum for an IEnumerable<byte>.  Checksums are really useful if the storage or transport you’re using is not 100% reliable – you send / store the data with its checksum.

When you read it back you calculate the checksum again. If it doesn’t match the one stored / sent with the data then there’s been a corruption (either in the data or the checksum).

Of course this only uses a byte so there’s a 1:255 chance that the data is corrupt but the checksum is correct nonetheless. There are many ways of creating checksums less prone being randomly correct despite the data being corrupt.  One has to weigh up the severity of this eventuality against the computational and space / transport cost of more resilient options.

2 thoughts on “Getting Sneaky with LINQ’s Aggregate Function

  1. Anonymous Coward

    It’s a nice application of Aggregate but sadly String.Join is much simpler

    1. tom Post author

      Indeed – looks like that sneaked in with .NET 2.0 and I missed it completely.
      The main point I was trying to get across though was that we shouldn’t think of LINQ as just a data interrogation tool, I end up using LINQ functionality all over the place.
      I will in future make a note to look for a more appropriate native function. We live and learn!

Comments are closed.