2017-09-10 54 views
-1

我知道有這個多個其他線程排序的名單,但我不能換我的頭周圍爲什麼它返回INT

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

所以我正確排序的項目列表。我假設,但無論我嘗試使用哪種解決方法,它都不會將其返回,因爲它無法將類型List<int>轉換爲int[]

在返回之前是否必須將變量items_sorted轉換?

+3

使用ToArray或將返回類型的方法更改爲List。如果你想要Array,請移除ToList調用。那隻會做一個多餘的副本。所以你應該做'return items.OrderBy(p => p).ToArray();' –

+0

最後只需使用toarray –

+0

你可以將你的返回參數定義爲一個數組,然後嘗試返回一個'List'。你爲什麼期望這個工作?如果出於某種原因想要能夠返回數組以及列表,您可能需要考慮'IEnumerable '作爲返回類型。 – oerkelens

回答

5

試試這個

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

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

,或者如果你想有一個完整的重構,並假設C#6.0或更高版本。

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

謝謝,這個答案就是它。我現在明白數組和列表之間的區別。 – William

+0

有點清潔是沒有別的 –