如何转换System.Linq.Enumerable.WhereListIterator 到列

2019-07-21 11:10发布

在下面的例子中,我怎么能很容易地转换eventScoresList<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); }

Answer 1:

你会使用ToList扩展:

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


Answer 2:

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

不工作?



Answer 3:

顺便说你为什么这样的特定类型的声明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);


文章来源: How to convert System.Linq.Enumerable.WhereListIterator to List?