Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a default IComparable<T> in a Linq OrderBy clause

I have a type which has a default sort order as it implements IComparable<T> and IComparable. I'm not getting the results I expect from LINQ , basically it looks as if the IComparable<T> which the type implements is not being applied.

I thought I would get the result I want with an expression in the form:

var result = MyEnumerable<T>.OrderBy(r => r); 

where T itself implements IComparable<T>. It's not happening.

I can see related questions where specific IComparable<T> classes are specified for the sort, but I can't find one which uses the default IComparable<T> implemented by T itself.

My syntax is clearly incorrect. What is the correct syntax please?

Thanks in advance.

like image 893
Mike Avatar asked Aug 09 '12 09:08

Mike


1 Answers

OrderBy uses the default comparer Comparer<T>.Default which in turn will default to use the IComparable<T> implementation for T, or the non-generic IComparable if the former does not exist.

This code works:

public class Program
{
    static void Main(string[] args)
    {
        var list = new List<Stuff>
                       {
                           new Stuff("one"),
                           new Stuff("two"),
                           new Stuff("three"),
                           new Stuff("four")
                       };

        var sorted = list.OrderBy(x => x);

        foreach (var stuff in sorted)
        {
            Console.Out.WriteLine(stuff.Name);
        }
    }
}

public class Stuff : IComparable<Stuff>
{
    public string Name { get; set; }

    public Stuff(string name)
    {
        Name = name;
    }

    public int CompareTo(Stuff other)
    {
        return String.CompareOrdinal(Name, other.Name);
    }
}
like image 139
Christoffer Lette Avatar answered Oct 11 '22 16:10

Christoffer Lette