Creating Custom Aggregate Functions in LINQ

Jomo Fisher—Adriane asks whether it’s possible to create your own aggregate function like Sum, Avg, Count, etc. For object queries, the answer is yes. First, let’s look at the actual implementation of Sum:

 

public static int Sum(this IEnumerable<int> source) {

    int sum = 0;

    foreach (int v in source) sum += v;

    return sum;

}

 

You can see this yourself if you have the LINQ Preview for C# installed. This is a straightforward function except for the ‘this’ on the first parameter. This makes Sum an extension method. I talk about this in more detail here.

 

So let’s write our own method and call it.

 

using System;

using System.Collections.Generic;

static class Program {

    public static int SumSquares(this IEnumerable<int> source) {

   int sum = 0;

        foreach (int v in source) sum += (v*v);

        return sum;

    }

    static void Main(string[] args) {

        int [] i = new int [] {1,2,3};

        Console.WriteLine(i.SumSquares());

    }

}

For DLinq, there’s no way to do this today.

 

This posting is provided "AS IS" with no warranties, and confers no rights.