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) filtered list, and then does it additionally filter this ThenBy(x => x.prop2) list ThenBy(x => x.prop2) ? In other words, is this equivalent

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

???

Because, obviously, this can be optimized by executing the sorting algorithm with a comparator:

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

If he does some kind of optimization, and the intermediate lists are not returned in the process, then how does he know how to do this? How do you write a class that optimizes method chains on itself? No difference.

+5
source share
1 answer

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

No. LINQ methods (at least usually) return queries , not the results of these queries.

OrderBy simply returns an object that, when you request it for an item, will return the first item in the collection specified by a specific order. But until you actually ask him about the result, he does nothing.

Note that you can also get a decent idea of ​​what is going on just by looking at what OrderBy returns. It returns an IOrderedEnumerable<T> . This interface has a CreateOrderedEnumerable method, which:

Performs the subsequent order of IOrderedEnumerable elements according to the key.

This method uses ThenBy to indicate that there is a subsequent order.

This means that you create all the ThenBy you want to use from the ThenBy and all ThenBy before you need to create one element in the result set.

For more information on how you can do this, see the John Skeet blog on the topic .

+7
source

Source: https://habr.com/ru/post/1241658/