C# List<string> add index to list console output

Viewed 599

In the bellow sample scenario i like to add the index of the item to the output console. And i just dont get it to work.

        public static void Main()
        {
            List<string> myList = new List<string> { "This", "is", "a", "test" };
            foreach (var item in myList)
                Debug.WriteLine(item);
        }

Something like this

Debug.WriteLine(item.index + " : : + item);

5 Answers

You can use Select to get an items with their index and print it out

List<string> myList = new List<string> { "This", "is", "a", "test" };
foreach (var item in myList.Select((value, index) => new { value, index }))
    Debug.WriteLine($"{item.value}:{item.index}");

You can also use IndexOf method, bit it'll return a first index and can cause a problem, if list has a duplicated items

foreach (var item in myList)
    Debug.WriteLine($"{item}:{myList.IndexOf(item)}");

Using a regular for loop also might be an option

for (int i = 0; i < myList.Count; i++) 
    Debug.WriteLine($"{myList[i]}:{i}");
public static void Main()
{
    int index = 0;
    List<string> myList = new List<string> { "This", "is", "a", "test" };
    foreach (var item in myList)
    {
        Debug.WriteLine(item + " " + index);
        index++;
    }
}

Remember that sometimes the simplest approach is the best, especially if you are a beginner. While Pavel's answer is also correct and preferable, if you need to ask this question you are just starting with programming, I would advice you to stick to general solutions (incrementing an index variable) which work in all programing languages. Once you are comfortable with those, move to language specific sugars

You can declare index variable:

List<string> myList = new List<string> { "This", "is", "a", "test" };
var index = 0;
foreach (var item in myList)
    Console.WriteLine($"{item} {index++}");

Or using simple for loop where i is alread declared and your loop more flexible - you can iterate from end to start and from start to end of List<T>:

List<string> myList = new List<string> { "This", "is", "a", "test" };
for (int i = 0; i < myList.Count; i++)
{
     Console.WriteLine($"{myList[i]} {i}");
}

The C# foreach does not have an inbuilt index. You can go with two approaches.

int index=-1;
foreach (var item in myList){
     index++;
     Debug.WriteLine(index + ":" + item);
}

or you can use the forloop

for (int i = 0; i < myList.Length; i++)
{
   var item = myList[i];
   Debug.WriteLine(i+ ":" + item);
}

You can use

myList.IndexOf(item)

to access item's index so your code should be:

public static void Main()
{
    List<string> myList = new List<string> { "This", "is", "a", "test" };
    foreach (var item in myList)
        Debug.WriteLine(item + ": " + myList.IndexOf(item));
}
Related