简体   繁体   English

如何对 c# 中的 arrays 数组进行排序?

[英]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).我正在尝试根据开始时间(这是第一个元素)对intervals列表进行排序。

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'错误 -CS1503 参数 1:无法从 'System.Collections.Generic.Comparer<int[]>' 转换为 '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;
}

You are right, in case of array you should use different syntax Array.Sort :你是对的,如果是数组,你应该使用不同的语法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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM