When working with LINQ in C#, it is recommended to pay attention to the order in which methods are chained, especially when using
Where
and OrderBy
methods. It is advised to call the Where
method before OrderBy
because
Where
filters the elements of the sequence based on a given condition and returns a new sequence containing only the elements that
satisfy that condition. Calling OrderBy
before Where
, may end up sorting elements that will be later discarded, which can
lead to inefficiency. Conversely, calling Where
before OrderBy
, will first filter the sequence to include only the elements
of interest, and then sort them based on the specified order.
What is the potential impact?
We measured at least 2x improvement in execution time. For more details see the Benchmarks
section from the More info
tab.