简体   繁体   中英

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[] ?

Do I have to convert the variable items_sorted before returning?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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