首页 > 解决方案 > C# 列表添加索引以列出控制台输出

问题描述

在下面的示例场景中,我喜欢将项目的索引添加到输出控制台。我只是不让它工作。

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

像这样的东西

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

标签: c#list

解决方案


您可以使用Select它们的索引获取项目并将其打印出来

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}");

您也可以使用IndexOf方法,如果列表中有重复项,它将返回第一个索引并可能导致问题

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

使用常规for循环也可能是一种选择

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

推荐阅读