如何将 System.Linq.Enumerable.WhereListIterator转换为列表?
在下面的示例中,如何轻松地将 eventScores
转换为 List
以便将其用作 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); }
In the below example, how can I easily convert eventScores
to List<int>
so that I can use it as a parameter for 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); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 ToList 扩展:
You'd use the ToList extension:
不起作用?
Doesn't work?
顺便问一下,为什么您要为 Scores 参数声明这样特定类型的 PrettyPrint,而不是仅将此参数用作 IEnumerable (我假设这就是您实现 ForEach 扩展方法的方式)?那么为什么不改变 PrettyPrint 签名并保持这个惰性评估呢? =)
像这样:
更新:
或者您可以避免像这样使用List.ForEach(不考虑字符串连接效率低下):
By the way why do you declare prettyPrint with such specific type for scores parameter and than use this parameter only as IEnumerable (I assume this is how you implemented ForEach extension method)? So why not change prettyPrint signature and keep this lazy evaluated? =)
Like this:
Update:
Or you can avoid using List.ForEach like this (do not take into account string concatenation inefficiency):