如何将System.Linq.Enumerable.WhereListIterator <int>转换为List <int>?</int> </int>

时间:2009-10-08 12:34:48

标签: c# linq action func

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

3 个答案:

答案 0 :(得分:22)

您将使用ToList扩展名:

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

答案 1 :(得分:9)

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

不起作用?

答案 2 :(得分:1)

顺便说一下为什么你要为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);