Finding the nearby points from an array I have the following code that takes a Point and a given tolerance value and looks for all other Points that fall within the tolerance from a Point array. Now this code is quite slow, does anyone know a faster way of doing this?

Also if you have any tips on how I can improve my coding style, if needed, that would be great.

private Point[] FindNearbyPoints(Point[] points, Point initialPoint, int tolerance)
{
    return points.Select(p =&gt; p)
                 .Where(p =&gt; (p.X &gt;= initialPoint.X - tolerance &amp;&amp; p.X &lt;= initialPoint.X + tolerance) &amp;&amp;
                             (p.Y &gt;= initialPoint.Y - tolerance &amp;&amp; p.Y &lt;= initialPoint.Y + tolerance))
                 .ToArray();
}
How many points are we talking about that makes performance slow?  If its a crazy amount, you could use a Range Partitioner and a Parallel.For.  But I would suggest outputting as a List&lt;Point&gt; rather than an array so that each parallel thread can merge the subset of points.  I'd rather not get into details about in this answer though.

One alternative is to check X or Y against the tolerance once:

private Point[] FindNearbyPoints(Point[] points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p =&gt; p)
                 .Where(p =&gt; (Math.Abs(p.X - initialPoint.X) &lt;= tolerance) &amp;&amp;
                             (Math.Abs(p.Y - initialPoint.Y) &lt;= tolerance))
                 .ToArray();
}


You could try making that an extension method in a public static class, such as:

public static Point[] FindNearbyPoints(this Point[] points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p =&gt; p)
                 .Where(p =&gt; (Math.Abs(p.X - initialPoint.X) &lt;= tolerance) &amp;&amp;
                             (Math.Abs(p.Y - initialPoint.Y) &lt;= tolerance))
                 .ToArray();
}


A bigger consideration is whether the return type must be Point[].  You might see some performance boost if you went with IEnumerable&lt;Point&gt;.  In fact the extension method could be more reachable if you changed the input signature a bit too.  Something like:

public static IEnumerable&lt;Point&gt; FindNearbyPoints(this IEnumerable&lt;Point&gt; points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p =&gt; p)
                 .Where(p =&gt; (Math.Abs(p.X - initialPoint.X) &lt;= tolerance) &amp;&amp;
                             (Math.Abs(p.Y - initialPoint.Y) &lt;= tolerance));
}


Other than that, your coding style looks fine.  Give these changes a try and see if performance is still an issue.  If it is, I'll try to find time to work up an example using a range partitioner.