-1

I have points struct array:

Point[] arr  = samples.pointsArray;

I need to retrieve from this array point where the X is the biggest number.

  Point maxX= (some logic);

Any idea how I can implement this?

Jay Walker
  • 4,576
  • 5
  • 46
  • 51
Michael
  • 12,788
  • 49
  • 133
  • 253

2 Answers2

4

Use the OrderBy and First LINQ operators:

Point minX = arr.OrderBy(p => p.X).First();

Point maxX = arr.OrderByDescending(p => p.X).First();
or
Point maxX = arr.OrderBy(p => p.X).Last();

Alternative solution (without using OrderBy):
How to get the Point with minimal X from an array of Points without using OrderBy?

Community
  • 1
  • 1
Rotem
  • 20,778
  • 6
  • 60
  • 108
1

Without needing to reorder the array (!?!) as suggested by @Rotem, you can simply do:

int maxX = arr.Max(p => p.X);
Point maxXPt = arr.First(p => p.X == maxX);

Note this is done in O(n) whereas the OrderBy method is O(n log n).

joce
  • 9,246
  • 18
  • 54
  • 71