Jonathan Wood
Jonathan Wood

Reputation: 67193

How is OrderBy Applied?

I have the following query:

var vendors = (from pp in this.ProductPricings
               join pic in this.ProductItemCompanies
               on pp.CompanyId equals pic.CompanyId into left
               from pic in left.DefaultIfEmpty()
               orderby pp.EffectiveDate descending
               group pp by new { pp.Company, SortOrder = (pic != null) ? pic.SortOrder : short.MinValue } into v
               select v).OrderBy(z => z.Key.SortOrder);

Does anyone know how the last OrderBy() is applied? Does that become part of the SQL query, or are all the results loaded in to memory and then passed to OrderBy()?

And if it's the second case, is there any way to make it all one query? I only need the first item and it would be very inefficent to return all the results.

Upvotes: 0

Views: 75

Answers (3)

icalderond
icalderond

Reputation: 19

Might use readable code, because as you write it is not understandable. You will have a problem in the future with the linq statement. The problem is that if your statement does not return any value the value will be null and whenever you make cause a exception.

You must be careful. I recommend you to do everything separately to understand the code friend.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152556

Well it will try to apply the OrderBy to the original query since you are still using an IQueryable - meaning it hasn't been converted to an IEnumerable or hydrated to a collection using ToList or an equivalent.

Whether it can or not depends on the complexity of the resulting query. You'd have to try it to find out. My guess is it will turn the main query into a subquery and layer on a "SELECT * FROM (...) ORDER BY SortOrder" outer query.

Upvotes: 1

COLD TOLD
COLD TOLD

Reputation: 13579

Given your specific example the order by in this situation most, likely be appliead as part of the expression tree when it getting build, there for it will be applied to sql generated by the LINQ query, if you would convert it to Enumarable like ToList as mentioned in another answer then Order by would be applied as an extension to Enumerable.

Upvotes: 1

Related Questions