How to convert System.Linq.Enumerable.WhereListIterator to List?

后端 未结 3 826
南方客
南方客 2020-12-16 14:54

In the below example, how can I easily convert eventScores to List so that I can use it as a parameter for prettyPrint?

相关标签:
3条回答
  • 2020-12-16 15:30
    var evenScores = scores.Where(i => i % 2 == 0).ToList();
    

    Doesn't work?

    0 讨论(0)
  • 2020-12-16 15:34

    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? =)

    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):

    var text = scores.Where(i => i % 2 == 0).Aggregate("Title", (text, score) => text + Environment.NewLine + score);
    
    0 讨论(0)
  • 2020-12-16 15:47

    You'd use the ToList extension:

    var evenScores = scores.Where(i => i % 2 == 0).ToList();
    
    0 讨论(0)
提交回复
热议问题