简体   繁体   English

返回int的排序列表

[英]return a sorted list of int

I know there are multiple other threads on this but I can't wrap my head around why it 我知道这上还有其他多个线程,但是我无法理解为什么

public int[] practice_5(List<int> items)
{
    if (items == null)
    {
        return null;
    }
    else
    {
        List<int> items_sorted = items.OrderBy(p => p).ToList();
        return items_sorted;
    }
}

So I have sorted the list of items correctly. 因此,我已经正确排序了项目列表。 I'm assuming but no matter what workaround I try, it won't return it because it can't convert type List<int> to int[] ? 我假设但无论尝试什么解决方法,它都不会返回它,因为它无法将List<int>类型转换为int[]吗?

Do I have to convert the variable items_sorted before returning? 返回之前是否必须转换变量items_sorted

Try this 尝试这个

public int[] practice_5(List<int> items)
{

    if (items == null)
    {
       return null;
    }
    else
    {
       return items.OrderBy(p => p).ToArray();
    }
}

or if you want a full refactor, and assuming C# 6.0 or higher. 或者如果您想进行全面重构,并假设使用C#6.0或更高版本。

public int[] practice_5(List<int> items)
{
    return items?.OrderBy(p => p).ToArray();   
}

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

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