7

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
  • 897
  • 4
  • 11
  • 28

7 Answers7

19

You can use String.Join to concatenate all lines:

string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891
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,274
  • 1
  • 22
  • 40
3
for (int i = 0; i < list.Count; i++)
    {
    Console.WriteLine(list[i])
    }
Unicorno Marley
  • 1,544
  • 13
  • 15
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
  • 62,844
  • 17
  • 138
  • 209
  • 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
  • 121,297
  • 15
  • 183
  • 252
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,274
  • 1
  • 22
  • 40
joce
  • 9,246
  • 18
  • 54
  • 71
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
  • 11,984
  • 10
  • 61
  • 68
  • 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