Iterate through a list without using a ForEach loop

I have a list of lines:

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

Is there a way to iterate through a list and display items in a console window without using a foreach loop, maybe using lambdas and delegates.

I would like the result to be like every one below on a new line:

The following fruits are available:
apples,
peaches,
mangoes

+5
source share
7 answers

You can use String.Jointo concatenate all strings:

string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);
+12
source

The most obvious is the old-fashioned vintage cycle for:

for (var i = 0; i < list.Count; i++)
{
    System.Console.WriteLine("{0}", list[i]);
}
+10
source
for (int i = 0; i < list.Count; i++)
    {
    Console.WriteLine(list[i])
    }
+3

linq

list.ForEach(Console.WriteLine);

ForEach , ForEach. .

+3

You can use a List<T>.ForEachmethod that is not really part of LINQ but looks like this:

list.ForEach(i => Console.WriteLine(i));
+1
source

Well, you can try the following:

Debug.WriteLine("The folowing fruits are available:");
list.ForEach(f => Debug.WriteLine(f));

This is the equivalent of a loop foreach, but without using a keyword foreach,

However, I do not know why you want to avoid a loop foreachwhen iterating over a list of objects.

0
source

There are three ways to iterate over a list:

//1 METHOD
foreach (var item in myList)
{
    Console.WriteLine("Id is {0}, and description is {1}", item.id, item.description);
}

//2 METHOD   
for (int i = 0; i<myList.Count; i++)
{ 
    Console.WriteLine("Id is {0}, and description is {1}", myList[i].id, myMoney[i].description);
}

//3 METHOD lamda style
myList.ForEach(item => Console.WriteLine("id is {0}, and description is {1}", item.id, item.description));
0
source

All Articles