Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
list
communitycreator

How to print all elements of a list in C#

Siddharth Singh

The List<T> class in the System.Collection.Generic namespace represents a collection of strongly typed elements and offers many ways to iterate and manipulate the list.

Below are some of the ways to print the items of a C# list.

Creating a list of strings

Here, we create a list of months.

var months = new List<string>();
months.Add("January");
months.Add("February");
months.Add("March");
months.Add("April");

Using the for loop

The simplest method to access the elements is by using the for loop. We can access the individual items in the list by their index, months[i], and then print the element using the Console.WriteLine() method.

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

Using the foreach loop

The foreach loop is a convenient construct to iterate through the items in a collection – it can be used to print the elements.

foreach(var month in months)
{
    Console.WriteLine(month);
}

Using the ForEach method

The List<T> class provides the ForEach(Action<T>) method to perform a specified action on each of the list elements.

months.ForEach(p => Console.WriteLine(p));

The code above can even be compacted a bit more by passing Console.WriteLine as a method group.

months.ForEach(Console.WriteLine);

Using the string.Join() method

The string.Join() method concatenates the list elements with a provided separator in between – it can be used to print the list of strings.

Console.WriteLine(string.Join(", ", months));

The below code example demonstrates all the ways discussed above to iterate through and print the elements of a C# list.

using System;
using System.Collections.Generic;

namespace ListPrinter
{
    class Program
    {
        static void Main(string[] args)
        {
            var months = new List<string>();
            months.Add("January");
            months.Add("February");
            months.Add("March");
            months.Add("April");

            //using for loop
            for(int i=0;i<months.Count;i++)
            {
                Console.WriteLine(months[i]);
            }

            //using foreach loop
            foreach(var month in months)
            {
                Console.WriteLine(month);
            }

            //using linq forEach
            months.ForEach(month => Console.WriteLine(month));

            //using linq forEach with static functi
            months.ForEach(Console.WriteLine);

            //using strings.join
            Console.WriteLine(string.Join(", ", months));
            
        }
    }
}
Various ways to print List elements in C#

RELATED TAGS

c#
list
communitycreator
RELATED COURSES

View all Courses

Keep Exploring