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)
Rectangle boundingBox = rectangles;
foreach (var rectangle in rectangles)
boundingBox = Rectangle.Union(boundingBox, rectangle);
Using a recursive function
static Rectangle GetRectUnionRecursive(params Rectangle rectangles)
return (rectangles.Length > 1)
: (rectangles.Length == 1)
static Rectangle GetRectUnionLINQ(params Rectangle rectangles)
return (rectangles.Length == 0)
.Aggregate(rectangles, (acc, rect) => Rectangle.Union(acc, rect));