Last Updated: February 25, 2016
·
1.442K
· buildcomplete

Using LINQ Aggregate effectively

I had some trouble figuring out how to use LINQ's aggregate,
one of the reasons is that I didn't find any good references on the net.

The problem solved; calculate the union between an arbitrary number of Rectangles

This was something I did at work recently when working on a image analysis program.

In the following, I will show 3 pieces of code doing just that in 3 different ways

  • One code piece using a loop
  • One code piece using a recursive function (mostly for the fun of it)
  • And Lastly a LINQ Expression using Aggregate

I think the examples will help illuminate how the LINQ expression works.

Using a loop

static Rectangle GetRectUnionLoop(params Rectangle[] rectangles)
{
    if (rectangles.Length == 0)
        return Rectangle.Empty;

    Rectangle boundingBox = rectangles[0];
    foreach (var rectangle in rectangles) 
    {
        boundingBox = Rectangle.Union(boundingBox, rectangle);

    }
    return boundingBox;
}

Using a recursive function

static Rectangle GetRectUnionRecursive(params Rectangle[] rectangles)
{
    return (rectangles.Length > 1)
        ? Rectangle.Union(rectangles[0],
            GetRectUnionRecursive(rectangles.Skip(1).ToArray()))
        : (rectangles.Length == 1)
            ? rectangles[0]
            : Rectangle.Empty;
}

Using LINQ

static Rectangle GetRectUnionLINQ(params Rectangle[] rectangles)
{
    return (rectangles.Length == 0)
        ? Rectangle.Empty
        : rectangles
            .Aggregate(rectangles[0], (acc, rect) => Rectangle.Union(acc, rect));
}