I have create a list like this:
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(7);
now if I want iterate it I should do:
foreach (int prime in list)
{
Console.WriteLine(prime);
}
How I can do this with a single line?
You can do it using List<T>.ForEach
:
list.ForEach(Console.WriteLine);
This employs a method group conversion to create an Action<int>
to call Console.WriteLine(int)
for each element of list
.
However, personally I would use the existing foreach
loop... it makes it clearer that you're expecting a side-effect for each iteration of the loop. Eric Lippert has a great blog post going into details of this philosophical objection.
This code is entirely safe - but more "clever", which is almost never a good thing when you're reading code. Ask yourself which code you're more likely to understand at a glance.
Note that this isn't accessing the data in the list "without iterating it" as per the question title - it's just that the iteration isn't obvious in your code. It's certainly still present in the ForEach
method.
See more on this question at Stackoverflow