Reputation: 3130
I have an array of complex types, let's call it Point
(see below), and I want to find all points that are within a given range of X values [minX, maxX]
. I need to do this search millions of times. How can I do this the fastest way?
public class Point {
public double X { get; set; };
public double Y { get; set; };
}
Point[] data;
I could do the search simply with data.Where(c => c.X > minX && c.x < maxX)
but this is too slow.
Note that I can sort the array by X
with data.sort(c => c.X)
apriori so theoretically I could return a chunk starting from the first element greater than minX
and stoping at the first element greater than maxX
. How can I do this?
Upvotes: 1
Views: 788
Reputation: 11973
try sorting the list first and then do a binary search on the list to find the index of min and max
Then you can do
.Skip(minIndex).Take(maxIndex - minIndex + 1)
Or, if you want it to be simple rather than speed then
.SkipWhile(x=>x <= minX).TakeWhile(x=>x < maxX)
Upvotes: 2