views:

64

answers:

3

I have this:

    var points = from p in ContextDB.Points
                 orderby p.PointInTime descending
                 where p.InstanceID == instanceId
                 && p.ParentPointID == null
                 && p.PointTypeID == currentPointTypeID
                 select p;

and this:

    var points = from p in ContextDB.Points
                 where p.InstanceID == instanceId
                 && p.ParentPointID == null
                 && p.PointTypeID == currentPointTypeID
                 orderby p.PointInTime descending
                 select p;

While I understand the use of both (and one generates an error later) I don't understand how they are different.

I did see questions like this elsewhere on STO, but I've not garnered what the answer to this question is, I'm afraid.

A: 

IOrderedQueryable the result of a query that results in a specific order and IQueryable has elements in an indeterminate order.

Lazarus
Am I correct in thinking that the first code sample will not order anything? If so, what's the point in being able to use `orderby` prior to `where`?
Matt W
@Matt-W : We'd have to look at the expression tree to determine how specifically each query is being processed. I suspect it's the first query that's generating the error for you. It wouldn't the first or the only Linq query that you can happily write and compile without error that then fails during execution, that's the nature of Linq.
Lazarus
A: 

A type implementing IOrderedQueryable<T> contains extra state to hold information about sorting.

IQueryable<T> normally represents an operation that will be performed later (and possibly in a completely different language on a different computer, e.g. with LINQ to SQL). A separate interface is needed because the next operation might be another sort, which needs to be treated differently to the first (to sort by column A and then B requires two LINQ operators to define, but the system needs to ensure that each key contributes to the overall sort).

Richard
+1  A: 

It's easy to see if you translate the query comprehension to its corresponding Linq extension methods. The return type of OrderBy() is IOrderedEnumerable<>. Where() returns IEnumerable<>. What your first expression does is first sort all of the Points, then select only the ones that match the where clause. The last operation applied is Where, thus the expression type is IEnumerable<>.

Which one is more efficient depends largely on the Linq provider you use. My money is on sorting last. Although I'd guess that the provider is smart enough to order the operations in the best order. You might want to check that.

Hans Passant