簡體   English   中英

為什么var Int32不是List <Int32> 在這個例子中

[英]Why is var Int32 not List<Int32> in this example

好的,我正在為另一個SO問題得到答案,我想出了以下函數來獲得一個獨特的int列表:

    static List<Int32> Example(params List<Int32> lsts)
    {
        List<Int32> result = new List<int>();

        foreach (var lst in lsts)
        {
            result = result.Concat(lst).ToList();
        }

        return result.Distinct().OrderBy(c => c).ToList();
    }

當我在VS2012中查看var時,它表示Int32類型而不是List<Int32> 如圖所示:

問題

var不應該是List<Int32> ??

你在參數類型聲明的末尾缺少一個[]

//                                            v-- this is missing in your code
static List<Int32> Example(params List<Int32>[] lsts)
{
    List<Int32> result = new List<int>();

    foreach (var lst in lsts)
    {
        result = result.Concat(lst).ToList();
    }

    return result.Distinct().OrderBy(c => c).ToList();
}

你被另一個編譯器錯誤誤導了。
您的參數不是數組。

您需要將參數更改為params List<Int32>[] lsts以使其成為列表數組。 (或者,更好的是, params IEnumerable<Int32>[] lsts

請注意,您也可以完全擺脫foreach循環並寫入

return lsts.SelectMany(list => list)
           .Distinct()
           .OrderBy(i => i)
           .ToList();

帶有關鍵字params必須是一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM