I recently worked on a project that included code to calculate the bounding box of a collection of rectangles. The code did more or less what you might expect – it iterated over the collection, and any time a new rectangle wasn’t contained by the current bounds, it enlarged the bounds to fit. There was nothing wrong with this, but I knew of a cute trick that could do the job with a fraction of the code. I wasn’t being paid to replace working code with cute tricks, so I left it as it was – when it comes to production code I’m not a fan of the “If it ain’t broke, let me take a crack at it” school of coding. So I thought I’d illustrate the idea here instead. Here’s a one-line implementation of the same logic, using the System.Windows.Rect type in WPF. (Note that this is a very simple value type, not a full UI element. It’s just 4 numbers.) public static Rect GetBounds( IEnumerable < Rect > rects) { return rects.Aggregate((currBounds, nextRect) => Rect .Union(currBounds, nextRect));
Read More...