Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a 'search a take best' function in LINQ?

Tags:

c#

linq

Greetings!

I'm looking for a way to search a collection for the object that best satisfies my criteria. Since I have to do this quite often, I was looking into how to execute the query using LINQ, but cannot find a simple way to do this that doesn't 'appear' to waste time.

A functional implementation would be:

collection.OrderByDescending(f => FitFunction(f)).First()

But this seems to unnecessarily do the sorting. I really just need a linear scan. The Min LINQ function returns the best fit, rather than the object which produces the best fit, and so doesn't seem useful.

For clarity, the non-LINQ code I would traditionally write (and have done so so many times):

T best;
float bestFit = something very low;

foreach (T ob in collection)
{
  float fit = FitFunction(ob);
  if (fit > bestFit)
  {
    bestFit = fit;
    best = ob;
  }
}
return best;

And I think I may just make my own extension method to do that; but it seems to me that there must already be a way to do this already within LINQ.

Thanks!

like image 886
Nick Gebbie Avatar asked Nov 12 '10 20:11

Nick Gebbie


Video Answer


1 Answers

This is essentially a Top-N problem based on a predicate with the additional constraint that N always is equal to 1. Unfortunately, there is no built-in LINQ operator that performs a TopN() operation ... but as you point out, it's not too hard to write one yourself.

The MoreLINQ library has an implementation of the MaxBy() operator, which allows you to specify a predicate - and would also work.

like image 133
LBushkin Avatar answered Sep 27 '22 18:09

LBushkin