17

在下面的示例中,如何轻松转换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); }
4

3 回答 3

32

您将使用 ToList 扩展:

var evenScores = scores.Where(i => i % 2 == 0).ToList();
于 2009-10-08T12:40:16.053 回答
10
var evenScores = scores.Where(i => i % 2 == 0).ToList();

不工作?

于 2009-10-08T12:39:14.753 回答
3

顺便说一句,为什么要为 score 参数声明具有这种特定类型的 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);
于 2009-10-08T12:44:02.093 回答