2009-10-11 56 views
8

如何將var類型轉換/轉換爲List類型?C# - var到List <T>轉換

這段代碼是給我的錯誤:

List<Student> studentCollection = Student.Get(); 

var selected = from s in studentCollection 
          select s; 

List<Student> selectedCollection = (List<Student>)selected; 
foreach (Student s in selectedCollection) 
{ 
    s.Show(); 
} 
+2

'var'不是一個類型,它只是您分配給該變量的任何表達式類型的佔位符。在這種情況下,查詢表達式的計算結果爲「IEnumerable 」。 – Joren 2009-10-11 17:58:41

回答

19

當你做對LINQ到對象的查詢,它會回報你的類型IEnumerable<Student> ,您可以使用ToList()方法創建來自IEnumerable<T>List<T>

var selected = from s in studentCollection 
          select s; 

List<Student> selectedCollection = selected.ToList(); 
+1

這個答案比我自己有更好的解釋。這應該被接受。 – 2009-10-11 17:55:58

+0

@CMS你好我的朋友。我在我的項目的問題中嘗試了這個解決方案。它不適合我。你能幫我解決這個問題嗎?: http://stackoverflow.com/questions/32839483/how-can-change-list-type – CoderWho 2015-09-29 10:40:45

3

可以調用ToList LINQ擴展方法

List<Student> selectedCollection = selected.ToList<Student>(); 
foreach (Student s in selectedCollection) 
{ 
    s.Show(); 
} 
1

請嘗試以下

List<Student> selectedCollection = selected.ToList(); 
8

在你的示例代碼var實際上是類型爲IEnumerable<Student>如果你正在做的是枚舉它,就沒有必要將其轉換爲一個列表

var selected = from s in studentCollection select s; 

foreach (Student s in selected) 
{ 
    s.Show(); 
} 

如果您確實需要它作爲一個清單,從LINQ的該ToList()方法將其轉換爲一個適合你。

相關問題