Subpar Web Dev
Subpar Web Dev

Reputation: 3260

Does LINQ know how to optimize "queries"?

Suppose I do something like

 var Ordered = MyList.OrderBy(x => x.prop1).ThenBy(x => x.prop2); 

Does MyList.OrderBy(x => x.prop1) return the filtered list, and then does it further filter that list by ThenBy(x => x.prop2)? In other words, is it equivalent to

var OrderedByProp1 = MyList.OrderBy(x => x.prop1);
var Ordered = OrderedByProp1.OrderBy(x => x.prop2);

???

Because obviously it's possible to optimize this by running a sorting algorithm with a comparator:

var Ordered = MyList.Sort( (x,y) => x.prop1 != y.prop1 ? x.prop1 < y.prop1 : ( x.prop2 < y.prop2 ) );

If it does do some sort of optimization and intermediate lists are not returned in the process, then how does it know how to do that? How do you write a class that optimizes chains of methods on itself? Makes no sense.

Upvotes: 5

Views: 251

Answers (1)

Servy
Servy

Reputation: 203828

Does MyList.OrderBy(x => x.prop1) return the filtered list

No. LINQ methods (at least typically) return queries, not the results of executing those queries.

OrderBy just returns an object which, when you ask it for an item, will return the first item in the collection given a particular ordering. But until you actually ask it for a result it's not doing anything.

Note you can also get a decent idea as to what's going on by just looking at what OrderBy returns. It returns IOrderedEnumerable<T>. That interface has a method CreateOrderedEnumerable which:

Performs a subsequent ordering on the elements of an IOrderedEnumerable according to a key.

That method is what ThenBy uses to indicate that there is a subsequent ordering.

This means that you're building up all of the comparers that you want to be used, from the OrderBy and all ThenBy calls before you ever need to generate a single item in the result set.

For more specifics on exactly how you can go about creating this behavior, see Jon Skeet's blog series on the subject.

Upvotes: 7

Related Questions