C# List sorting with multiple range

The LINQ way is to just do this (assuming you want to end up with a sorted array, the ToArray bit isn’t needed):

var sorted = values.OrderBy( value => value < 0 ).ThenBy( Math.Abs ).ToArray();

The only reason I’m showing that is so you have can compare it with the non-LINQ approach using a comparer:

public class MyComparer : IComparer<double>
{
    public int Compare( double x, double y )
    {
        if( x < 0 )
        {
            if( y >= 0 ) return 1;
            return -x.CompareTo( y );
        }
        else
        {
            if( y < 0 ) return -1;
            return x.CompareTo( y );
        }
    }

    public static MyComparer Instance{ get; } = new MyComparer();

    private MyComparer() {}
}

And then to use it:

Array.Sort( values, MyComparer.Instance);

The point is it’s a lot more code (and many more places to mess up the comparison). This also sorts the array in place (where the LINQ version will make a copy if you ask it to).

Leave a Comment