在下面的例子中,我怎么能很容易地转换eventScores
到List<int>
,这样我可以把它作为一个参数prettyPrint
?
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); }
你会使用ToList扩展:
var evenScores = scores.Where(i => i % 2 == 0).ToList();
var evenScores = scores.Where(i => i % 2 == 0).ToList();
不工作?
顺便说你为什么这样的特定类型的声明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);