我有一個基本的疑問,但我無法弄清楚我自己。 我有一段代碼如下:用列表替換IEnumerable
List<string> List = new List<string>();
List.Add("A");
List.Add("B");
List.Add("sam);
List.Add("Sed");
IEnumerable<string> names = from n in List where (n.StartsWith("S")) select n;
爲什麼上面的代碼請求一個顯式轉換如果IEnumerable的被替換的具體實施,即,列表。
即如果我使用:
List<string> names = from n in List where (n.StartsWith("S")) select n;
具有編譯錯誤。
我可以盲目使用Ienumerable,但我想知道當我使用List時發生了什麼?
只是有一個問題,當我做對列表的操作名單=新名單();(在這種情況下,名稱檢查) ,並LINQ的操作輸出將在IEnumerable的始終?輸入是List –
user2630764
@ user2630764 ling擴展方法將返回一個「IEnumerable」,與您所查詢的任何「IEnumerable 」無關;它可以是一個列表,一個數組,一個枚舉等,它不會有問題。此外,重要的是你知道linq是* lazy *。這意味着只有在實際枚舉它時(例如使用'foreach'語句或'ToList()'),查詢的答案纔會被枚舉。 –
InBetween