I implement the following algorithm in order to find a point from a given X value in a sorted list with the same distance between each X values. Here's an example of my list content with a delta of 10:
(687;10)
(12;20)
(24;30)
(10125;40)
(0;50)
(111;60)
(-2;70)
- The delta can be any float number;
- The list can be up to 2.000.000pts so it needs to be as fast as possible;
- I can't change the type of the points container (IPointList from ZedGraph).
Here's the code:
private ZedGraph.PointPair findPoint(ZedGraph.CurveItem curve, double x)
{
if (curve.NPts == 1)
return curve.Points[0];
// Look for the min and max value
double min = curve.Points[0].X;
double max = curve.Points[curve.NPts - 1].X;
double delta = curve.Points[1].X - min;
// Prevent error if mouse is out of bounds.
if (x > max)
x = curve.Points[curve.NPts - 1].X;
else if (x < min)
x = curve.Points[0].X;
double index = (x - min) / delta;
int nearestIndex = (int)Math.Round(index, 0);
if (nearestIndex < curve.NPts)
{
return curve.Points[nearestIndex];
}
return curve.Points[curve.NPts - 1];
}
IPointList
doesn't implementIEnumerable<PointPair>
or evenIEnumerable
. I assume you can't just add that toIPointList
? \$\endgroup\$