如何将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(不要考虑字符串连接效率低下):
上述就是C#学习教程:如何将System.Linq.Enumerable.WhereListIterator 转换为List ?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/961033.html