小编Jam*_*rom的帖子

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

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

// 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)

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

这存在吗?

c# linq max

8
推荐指数
1
解决办法
360
查看次数

标签 统计

c# ×1

linq ×1

max ×1