chaoz
chaoz

Reputation: 5

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;
}

Upvotes: 0

Views: 422

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

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;
}

Upvotes: 3

Related Questions