How do you sort array of arrays in c#?

I'm trying to sort a list of intervals based on start time (which is the first element).

public static int[][] SortIntervals(int[][] intervals)
{
    intervals.Sort(Comparer<int[]>.Create((a, b) => a[0].CompareTo(b[0]))); // error
    return intervals;
}

Error -CS1503 Argument 1: cannot convert from 'System.Collections.Generic.Comparer<int[]>' to 'System.Array'

I can sort a list of intervals just fine, maybe I'm missing the correct syntax for it.

public static List<int[]> SortIntervals(List<int[]> intervals)
{
    intervals.Sort(Comparer<int[]>.Create((a, b) => a[0].CompareTo(b[0])));
    return intervals;
}

1 answer

  • answered 2022-01-13 04:57 Dmitry Bychenko

    You are right, in case of array you should use different syntax Array.Sort:

    public static int[][] SortIntervals(int[][] intervals)
    {
        if (null == intervals)
            throw new ArgumentNullException(nameof(intervals));
    
        Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));    
    
        return intervals;
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum