user1527762
user1527762

Reputation: 957

Iterating through a list with out using ForEach loop

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

Upvotes: 9

Views: 66370

Answers (7)

daniele3004
daniele3004

Reputation: 13910

There are three ways to iterate 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));

Upvotes: 1

joce
joce

Reputation: 9892

Well, you could try the following:

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

It's the very equivalent of a foreach loop, but not using the foreach keyword,

That being said, I don't know why you'd want to avoid a foreach loop when iterating over a list of objects.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can use List<T>.ForEach method, which actually is not part of LINQ, but looks like it was:

list.ForEach(i => Console.WriteLine(i));

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65496

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.

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460098

You can use String.Join to concatenate all lines:

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

Upvotes: 22

Unicorno Marley
Unicorno Marley

Reputation: 1884

for (int i = 0; i < list.Count; i++)
    {
    Console.WriteLine(list[i])
    }

Upvotes: 3

Philip Kendall
Philip Kendall

Reputation: 4314

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]);
}

Upvotes: 11

Related Questions