如何将System.Linq.Enumerable.WhereListIterator 转换为List ?

在下面的示例中,如何轻松地将eventScores转换为List以便我可以将其用作prettyPrint的参数?

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

您将使用ToList扩展名:

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

不起作用?

顺便说一下,为什么你为score参数声明具有这种特定类型的prettyPrint,而不是仅将此参数用作IEnumerable(我假设这是你实现ForEach扩展方法的方式)? 那么为什么不改变prettyPrint签名并保持这种懒惰的评估呢? =)

像这样:

 Action, 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);