8

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

user1527762
  • 927
  • 4
  • 13
  • 29

7 Answers7

21

You can use String.Join to concatenate all lines:

string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
11

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]);
}
Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
3
for (int i = 0; i < list.Count; i++)
    {
    Console.WriteLine(list[i])
    }
Unicorno Marley
  • 1,744
  • 1
  • 14
  • 17
3

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.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • 1
    Note that `List.ForEach` is not a LINQ method, but just a plain old regular `List` method; LINQ methods are never purely called for their side effects as `List.ForEach` is. – Philip Kendall Mar 11 '13 at 23:25
  • Yeah technically I agree but these features are usually lumped together with linq :-) – Preet Sangha Mar 12 '13 at 01:15
1

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));
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

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.

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
joce
  • 9,624
  • 19
  • 56
  • 74
1

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));
daniele3004
  • 13,072
  • 12
  • 67
  • 75
  • The brevity of method 3 is popular with some devs but it has the disadvantage that you cannot "break" -out of it, if processing can be curtailed before all items have been accessed. – Zeek2 Jun 07 '18 at 13:58