2009-10-08 151 views
8

在下面的示例中,如何將eventScores輕鬆轉換爲List<int>,以便我可以將它用作prettyPrint的參數?如何將System.Linq.Enumerable.WhereListIterator <int>轉換爲列表<int>?

Console.WriteLine("Example of LINQ's Where:"); 
List<int> scores = new List<int> { 1,2,3,4,5,6,7,8 }; 
var evenScores = scores.Where(i => i % 2 == 0); 

Action<List<int>, string> prettyPrint = (list, title) => 
    { 
     Console.WriteLine("*** {0} ***", title); 
     list.ForEach(i => Console.WriteLine(i)); 
    }; 

scores.ForEach(i => Console.WriteLine(i)); 
prettyPrint(scores, "The Scores:"); 
foreach (int score in evenScores) { Console.WriteLine(score); } 

回答

20

您應該使用ToList擴展:

var evenScores = scores.Where(i => i % 2 == 0).ToList(); 
+5

Pfft ,慢碼! i =>(i&1)== 0 – leppie

+23

Pfft,微分優化不受分析驅動。迭代器的創建和複製到列表的速度將比微觀優化數學節省的成本慢數百倍。 *優化緩慢的東西* –

9
var evenScores = scores.Where(i => i % 2 == 0).ToList(); 

不起作用?

1

順便說你爲什麼聲明prettyPrint與這種特定類型的得分參數,比使用此參數只爲IEnumerable(我假設你這是怎麼實現的ForEach擴展方法)?那麼爲什麼不改變prettyPrint簽名並保持這種懶惰評估? =)

像這樣:

Action<IEnumerable<int>, string> prettyPrint = (list, title) => 
{ 
    Console.WriteLine("*** {0} ***", title); 
    list.ForEach(i => Console.WriteLine(i)); 
}; 

prettyPrint(scores.Where(i => i % 2 == 0), "Title"); 

更新:

或者你能避免使用List.ForEach這樣的(不考慮字符串連接效率低下):

var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score); 
+1

也許是因爲'ForEach'是'List '類中的一種內置方法。您必須編寫自己的擴展方法才能使用'ForEach'和'IEnumerable '。 – LukeH

相關問題