Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

action

func

In the below example, how can I easily convert eventScores to List<int> so that I can use it as a parameter for 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); }
like image 219
Edward Tanguay Avatar asked Oct 08 '09 12:10

Edward Tanguay


People also ask

How do I turn an IEnumerable into a List?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

What is ToList () in C#?

The ToList<TSource>(IEnumerable<TSource>) method forces immediate query evaluation and returns a List<T> that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.

What is Linq enumerable?

ElementAt<TSource>(IEnumerable<TSource>, Int32) Returns the element at a specified index in a sequence. ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index) Returns the element at a specified index in a sequence or a default value if the index is out of range.


3 Answers

You'd use the ToList extension:

var evenScores = scores.Where(i => i % 2 == 0).ToList();
like image 118
Pete OHanlon Avatar answered Oct 23 '22 00:10

Pete OHanlon


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

Doesn't work?

like image 45
Justin Niessner Avatar answered Oct 23 '22 00:10

Justin Niessner


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);
like image 3
Dzmitry Huba Avatar answered Oct 23 '22 00:10

Dzmitry Huba