Enumerable.OrderBy "compares keys using the default comparison. Default ", which, in turn, will use your implementation of IComparable<T> .
If so, is it better to encapsulate the sorting criteria in the MyData class (by implementing the above interfaces) or specify the criteria in the LINQ query (without MyData, which implements these interfaces)? What are the pros and cons of these two options?
So first, yes.
Both approaches have advantages.
The implementation of IComparable<T> suggests that the type has a natural order. When it's true, I like to implement this interface. The main professional, from a LINQ point of view, is that you simplify your LINQ queries (a bit). However, my main professional is more likely to offer a โnaturalโ order for this type, which in turn adds clarity to your API.
The primary profile for defining criteria in the LINQ query itself is flexibility. This allows you to sort by any number of criteria - without limiting yourself to a specific type, defined in the type itself. If a type does not have a โnaturalโ sort order (i.e., it does not represent something that is a โquantityโ, everything is at its discretion or similar), I would personally use this method.
source share