-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,654
  • 5
  • 47
  • 53
Michael
  • 13,950
  • 57
  • 145
  • 288

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
  • 21,452
  • 6
  • 62
  • 109
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,624
  • 19
  • 56
  • 74