C# 如何将 System.Linq.Enumerable.WhereListIterator<int> 转换为 List<int>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1537528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert System.Linq.Enumerable.WhereListIterator<int> to List<int>?
提问by Edward Tanguay
In the below example, how can I easily convert eventScores
to List<int>
so that I can use it as a parameter for prettyPrint
?
在下面的示例中,如何轻松转换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); }
采纳答案by Pete OHanlon
You'd use the ToList extension:
您将使用 ToList 扩展名:
var evenScores = scores.Where(i => i % 2 == 0).ToList();
回答by Justin Niessner
var evenScores = scores.Where(i => i % 2 == 0).ToList();
Doesn't work?
不起作用?
回答by Dzmitry Huba
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? =)
顺便说一句,为什么您为分数参数声明了具有这种特定类型的prettyPrint,而不是仅将此参数用作IEnumerable(我假设这就是您实现ForEach 扩展方法的方式)?那么为什么不改变prettyPrint 签名并保持这个懒惰的评估呢?=)
Like this:
像这样:
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");
Update:
更新:
Or you can avoid using List.ForEach like this (do not take into account string concatenation inefficiency):
或者你可以避免像这样使用 List.ForEach(不考虑字符串连接效率低下):
var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score);