简体   繁体   English

如何转换System.Linq.Enumerable.WhereListIterator <int> 列表 <int> ?

[英]How to convert System.Linq.Enumerable.WhereListIterator<int> to List<int>?

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); }

您将使用ToList扩展名:

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

不起作用?

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)? 顺便说一下,为什么你为score参数声明具有这种特定类型的prettyPrint,而不是仅将此参数用作IEnumerable(我假设这是你实现ForEach扩展方法的方式)? So why not change prettyPrint signature and keep this lazy evaluated? 那么为什么不改变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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM