Of all objects matching a condition, find the one closest to a position. Supposedly a very common problem. The current code looks like this:
protected Foo FindClosestFooMatching (Vec pos, Func<Foo, bool> matches)
{
float bestDist = float.MaxValue;
Foo bestFoo = null;
foreach (Foo foo in AllFoos()) {
if (matches (foo)) {
float dist = pos.Dist (foo.Center);
if (dist <= bestDist) {
bestDist = dist;
bestFoo = foo;
}
}
}
return bestFoo;
}
I’m thinking of several ways to refactor this code, but failed to find a really nice one yet. If you’ve got a minute, give it a shot. 🙂
Edit: Regarding Eric’s questions. It’s a standard 3D space with Euclidian metric (= fast). Point clustering and junk query likelihood is unknown.
Can’t compile right now, but I hope this does the job.
The important point to notice here is that every operation, including OrderBy, is subject to deferred execution, so the performance should be ok.
This would be a nicer looking solution:
Edit: I found this question to be a valuable source in this issue. Since OrderBy actually orders the whole list first, it’s of course slow (as Eric said, O(n log n). A better solution would be to use Aggregate or Jon Skeet’s propsed MinBy extension (see above link for examples).
I actually love the MoreLinq solution, as it reduces the code to: