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); }
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();
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.
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.
You'd use the ToList extension:
var evenScores = scores.Where(i => i % 2 == 0).ToList();
var evenScores = scores.Where(i => i % 2 == 0).ToList();
Doesn't work?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With