views:

252

answers:

1

Is anyone aware of whether there are there any built-in capabilities in the LINQ library (or a publicly available utility library) for optimized operations on IOrderedEnumerable<T>, as opposed to IEnumerable<T>?

For example, in theory, the Contains<T>() extension could potentially be optimized to use binary search when it is applied to a finite IOrderedEnumerable<T> and T is IComparable.

Another example, would be an optimized version of Distinct<T>() that would be deferred and streamable (since on an ordered, comparable collection you can always use skip/match techniques to produce a distinct set).

+5  A: 

There are problems there...

  • A binary search can't be executed on an IOrderedEnumerable<T>, as it ideally needs indexer access into a list/array. So it would have to call something like ToList()/ToArray() first
  • Distinct works on the T items, but OrderBy works on some facet of each T - it isn't quite the same, unless you happen to know that it is ordered by item=>item; which is rarely the case (and hard to prove).
Marc Gravell
Excellent points ... I didn't consider implications of what ordering a collection could mean in all cases.
LBushkin
Nitpick: you don't need to know that it's ordered by item=>item, as long as you know that the IEqualityComparer passed to Distinct obeys the same ordering as that used by OrderBy. As you say, though, you can't know this in all cases. I guess you could capture the IComparer used by OrderBy/ThenBy, and use that, but it's likely way too much work.
Roger Lipscombe