C# Programming Language: How to Traverse a List

Jesse L
3 min readApr 27, 2022

Hi everyone, welcome back. In this example, we will be going over how to traverse a list in C#. Lists can be used to store a collection of data, similar to that of an Array. The key difference between a List and an Array is that a List is resizable and an array is not. This leaves the List as a great option when wanting to modify a collection of data. With this introduction out of the way, let’s get into it.

Creating List

Let’s start by creating a List. Before we can create the ArrayList, we need to make sure we have our List import, which is included within the System.Collections.Generic package:

using System.Collections.Generic;

Now, we can successfully create our List:

List<int> myList = new List<int>();

So now, we have successfully created our List variable of the integer data type named myList. When we create our List, we need to specify the data type. As we can see in the example above, we have used the ‘int’ data type. We can use other data types as well, such as the string or boolean data types.

Adding Elements Into The List

Now, let’s try to add elements into our List. We can do this by using the built in Add() function that is provided. Let’s see an example:

List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
myList.Add(3);
Console.WriteLine(String.Join(" ", myList));
Output:
1 2 3

In the example above, we can see that we added a few different numbers/integers into our List by using the Add() function. We can verify that they were successfully added, by printing our List and checking the output.

Traversing a List

Finally, we can see how to traverse a List. We can use a for loop to get each individual element and use the Count property to get the number of elements within the List. This can be used to tell the for loop how many times to run. Let’s see an example:

List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
myList.Add(3);
for(int i = 0; i < myList.Count; i++)
{
Console.WriteLine(myList[i]);
}

--

--

Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.