Suppose I have a list of elements (e.g. Posts) and I want to find the first element according to some non-trivial ordering (e.g. PublishDate and then CommentCount as a tie-breaker). The natural way to do this with LINQ is as follows:
posts.OrderBy(post => post.PublishDate).ThenBy(post => post.CommentsCount).First()
However, the micro-optimizer in me is worried that calling OrderBy actually costs me O (n * lgn) to sort the entire list when I really need the O (n) find-minimum operation.
So LINQ is smart enough to return something from OrderBy (), which knows how to optimize subsequent calls to First ()? If not, what's the best way to do this out of the box? (I can always write my own implementation of FindMinimumItem, but this seems like overkill).
c # complexity-theory linq sql-order-by
Avish
source share