Title: Use LINQ to find a bounding box for a list of PointF in C#
This example shows how to use LINQ to find a bounding box for a list of PointF. When you click on the program's PictureBox, it adds points to the list and shows the bounding box.
The following method finds the bounding box.
// Find the list's bounding box.
private Rectangle BoundingBox(IEnumerable<Point> points)
{
var x_query = from Point p in points select p.X;
int xmin = x_query.Min();
int xmax = x_query.Max();
var y_query = from Point p in points select p.Y;
int ymin = y_query.Min();
int ymax = y_query.Max();
return new Rectangle(xmin, ymin, xmax - xmin, ymax - ymin);
}
Notice that the method takes as a parameter an IEnumerable<Point>, so it can take any enumerable object as a parameter. In this example, the program uses a List<Point>, but the method could also process an array of Point or some other collection class holding Point.
The method first makes a LINQ query to select the points' X coordinates. It then uses the query's Min and Max methods to get the minimum and maximum X values.
It repeats those steps to get the minimum and maximum Y values. It finishes by using the minimum and maximum values to build a Rectangle, which it returns.
Note that LINQ defers execution until the query is actually needed. In this case, that means the query is not actually executed until the program calls Min to find xmin.
The following code shows how the program uses the BoundingBox method.
// Draw the points and the bounding box.
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
// Draw the points.
foreach (Point point in Points)
e.Graphics.DrawEllipse(Pens.Red,
point.X - 2, point.Y - 2, 5, 5);
// Draw the bounding box.
if (Points.Count > 1)
e.Graphics.DrawRectangle(Pens.Green,
BoundingBox(Points));
}
This code loops through the points and draws them. Then if the Points list holds more than 1 Point, the code calls the BoundingBox method and draws the Rectangle it returns.
Download the example to experiment with it and to see additional details.
|