Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does LINQ sort items by a given criteria?

Tags:

c#

.net

linq

Suppose we have a MyData class which implements the IComparable<MyData> and IComparable interfaces. Then we have a list containing many of MyData elements and a LINQ query to get a sorted list.

public class MyData : IComparable<MyData>, IComparable
{
    ...

    public int CompareTo(MyData value)
    {
        // TODO
    }

    public int CompareTo(object value)
    {
        if (value == null)
            return 1;

        if (value.GetType() == typeof(MyData))
        {
            MyData rightValue = (MyData)value;
            return (this.CompareTo(rightValue));
        }
        else throw new ArgumentException("Object is not a " + typeof(MyData) + ".");
    }
}

// main method
List<MyData> list = new List<MyData>();
...
var items = from item in list
            orderby item descending
            select item;

When LINQ sorts the elements within the list, does it use the implementation of IComparable interface in the MyData class?

If the answer is yes, is it better to encapsulate the sort criteria in the class MyData (by implementing the above interfaces) or specify the criteria in a LINQ query (without MyData that implements these interfaces)? What are the pros and cons of these two choices?

like image 893
enzom83 Avatar asked Dec 27 '22 06:12

enzom83


1 Answers

Enumerable.OrderBy "compares keys by using the default comparer Default", which in turn will use your IComparable<T> implementation.

If the answer is yes, is it better to encapsulate the sort criteria in the class MyData (by implementing the above interfaces) or specify the criteria in a LINQ query (without MyData that implements these interfaces)? What are the pros and cons of these two choices?

So first, the answer is yes.

Both approaches have advantages.

Implementing IComparable<T> suggests that the type has a natural ordering. When this is true, I like implementing this interface. The main pro, in terms of LINQ, is that you simplify your LINQ queries (a bit). However, my main pro is more the suggestion of a "natural" order for that given type, which, in turn, adds to the clarity of your API.

The main pro of specifying the criteria in the LINQ query itself is flexibility. This allows you to sort by any number of criteria - not restricting yourself to a given sort defined in the type itself. If there isn't a "natural" sorting order for the type (ie: it's not representing something that is a "quantity" all on its own or similar), then I'd personally use this method.

like image 153
Reed Copsey Avatar answered Jan 16 '23 17:01

Reed Copsey