开发者

How to do a 'search a take best' function in 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜