开发者

LINQ 2 Objects Having clause

Given a collection of MyType { int Index, string Name } what would be the technically efficient way of getting Min/Max index items?

we use:

MyType minIndexItem = items.Single(t=>
   t.Index == items.Min(t=>
      t.Index));

which doesn't look exactly elegant. We'd like to stick 开发者_Python百科to lambda syntax too and we are looking for the most technically efficient approach, not sugar'ish things like extension methods etc.

Thanks.


It could be

  (from item in items select item order by item.Index).First() 

Pretty fast if the Index field has a db index.


Sorting it will be the simple way to do it for LINQ-to-RDBMS, but probably not for LINQ-to-Objects, because the sorting may be expensive and runs in O(nlogn).

You can use LINQ aggregation to get the lowest or highest. This runs through the entire collection exactly once, an is always O(n). For example, to get the lowest item:

items.Aggregate((current, next) => next.Index < current.Index ? next : current);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜