This project has moved and is read-only. For the latest updates, please go here.


Aug 29, 2011 at 6:55 AM
Edited Aug 29, 2011 at 7:05 AM

Is there a way to optimize LINQ queries such as Where(predicate).Reverse() or maybe Reverse().Where(predicate)? Currently, the first expression results in Reverse pulling out the entire output of Where and the second expression results in Where testing its predicate on the entire output of Reverse.

UPDATE: The predicate is testing on the Key using comparison operators. Basically, I want to traverse the dictionary both forward and backward from any key.

Aug 29, 2011 at 7:20 AM

Where(predicate).Reverse() is optimizable (assuming the predicate itself is selecting only a subset of the keys).

Technical details: PersistentDictionary.Where returns a PersistentDictionaryLinqKeyValueEnumerable object, which will walk only a subset of the keys. The Reverse() method is called on the PersistentDictionaryLinqKeyValueEnumerable and tells it to walk the keys in the opposite order.

So, using the latest release I expect these cases to be optimized:


var dict = new PersistentDictionary<int, string>();
var q = dict.Where(x.Key > 100).Reverse();
var q2 = dict.Where(x.Key < 1000).Reverse();


Note that the type of the dictionary is important! If you change the type of dict in the example from PersistentDictionary to IDictionary then the query will be run using the LINQ extension operators, which will always do a full enumeration.

Aug 29, 2011 at 8:31 AM

Thank you for your quick response. It turned out I tested on the value (somehow overlooked it). Now Where().Reverse() works perfectly!