Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a list with out using ForEach loop

Tags:

c#

lambda

I have a list of list of strings:

var list = new List<string> {"apples","peaches", "mango"};

Is there a way to iterate through the list and display the items in a console window without using foreach loop may be by using lambdas and delegates.

I would like to the output to be like below each in a new line:

The folowing fruits are available:
apples
peaches
mango

like image 672
user1527762 Avatar asked Mar 11 '13 23:03

user1527762


4 Answers

You can use String.Join to concatenate all lines:

string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);
like image 119
Tim Schmelter Avatar answered Oct 21 '22 05:10

Tim Schmelter


By far the most obvious is the good old-fashioned for loop:

for (var i = 0; i < list.Count; i++)
{
    System.Console.WriteLine("{0}", list[i]);
}
like image 20
Philip Kendall Avatar answered Oct 21 '22 05:10

Philip Kendall


for (int i = 0; i < list.Count; i++)
    {
    Console.WriteLine(list[i])
    }
like image 25
Unicorno Marley Avatar answered Oct 21 '22 03:10

Unicorno Marley


I love this particular aspect of linq

list.ForEach(Console.WriteLine);

It's not using a ForEach loop per se as it uses the ForEach actor. But hey it's still an iteration.

like image 32
Preet Sangha Avatar answered Oct 21 '22 05:10

Preet Sangha