从C#3.5中的集合中返回最合适的项目,只需一两行

Jam*_*rom 8 c# linq max

以下是我生活中基本上写过数千次的示例代码:

// find bestest thingy
Thing bestThing;
float bestGoodness = FLOAT_MIN;
foreach( Thing x in arrayOfThings )
{
  float goodness = somefunction( x.property, localvariable );
  if( goodness > bestGoodness )
  {
    bestGoodness = goodness;
    bestThing = x;
  }
}
return bestThing;
Run Code Online (Sandbox Code Playgroud)

在我看来,C#应该已经有一些东西可以做到这一点.就像是:

return arrayOfThings.Max( delegate(x)
  { return somefunction( x.property, localvariable ); });
Run Code Online (Sandbox Code Playgroud)

但是这不会返回事物(或事物的索引,这将是好的),它返回适合度值.

也许是这样的:

var sortedByGoodness = from x in arrayOfThings 
  orderby somefunction( x.property, localvariable ) ascending 
  select x;
return x.first;
Run Code Online (Sandbox Code Playgroud)

但是这样做整个阵列都可能太慢了.

这存在吗?

Mik*_*ain 2

我认为在标准 LINQ 中如果不对可枚举对象进行排序(一般情况下很慢),这是不可能的,但您可以使用MaxBy()MoreLinq 库中的方法来实现这一点。我总是在我的项目中包含这个库,因为它非常有用。

http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/MaxBy.cs

(该代码实际上看起来与您所拥有的非常相似,但是是通用的。)

  • 实际上,您可以通过使用“Aggregate”在普通 LINQ 中进行排序而无需进行排序,但除了最简单的情况之外,在所有情况下它最终都非常丑陋。最好使用某种“MaxBy”扩展方法。 (2认同)