Use LINQ to find the largest and smallest X and Y values in an array of PointF in C#

This example makes an array containing PointF values. The following code finds and displays the largest and smallest X and Y values in the data.

// Use LINQ to find the minimum and maximum
// X and Y values in the data.
private void Form1_Load(object sender, EventArgs e)
{
// This query selects all X values.
var x_query = from PointF p in Values select p.X;

// Get the minimum and maximums of the resulting list.
float xmin = x_query.Min();
float xmax = x_query.Max();

// This query selects all Y values.
var y_query = from PointF p in Values select p.Y;

// Get the minimum and maximums of the resulting list.
float ymin = y_query.Min();
float ymax = y_query.Max();

// Display the results.
txtXmin.Text = xmin.ToString();
txtXmax.Text = xmax.ToString();
txtYmin.Text = ymin.ToString();
txtYmax.Text = ymax.ToString();
}

The code first defines a LINQ query named x_query that selects all of the X values from the PointFs in the Values array. It then uses the result's Min method to get the minimum value from the X values that were selected. Similarly it uses the Max method to get the largest value from the selected values.

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 code repeats these steps to find the minimum and maximum Y values.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.