Print elements from a list

1

Is there a way to read the values that are in a list and display them in the console?

I tried it like this, but it does not work

Console.WriteLine(lista);
    
asked by anonymous 14.06.2017 / 18:19

2 answers

9

You have to go through all the items in the list and print them.

foreach(var elemento in lista)
{
    Console.WriteLine(elemento);
}

If you want a one-liner version. This only works for List , nothing else.

lista.ForEach(Console.WriteLine);

See working in .NET Fiddle.

Warning : If the list is of objects, this will call the ToString() method of the objects. If this is not the desired behavior, you can either print property by property, or even create a method that returns a string with the properties you want to display.

Example using the properties

foreach(var elemento in lista)
{
    Console.WriteLine(elemento.Propriedade);
    Console.WriteLine(elemento.OutraPropriedade);
}
    
14.06.2017 / 18:21
0
Foreach([tipo lista] lista on [nome da lista]{

    Console.WriteLine(lista);

}

Where [List Type] is the type (string, float, double, int, object) and list name is the name you gave, eg

List<string> listaString = new List<String>();
Foreach(string lista on listaString {
    Console.WriteLine(lista);
}
    
14.06.2017 / 18:25