c# - 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);
解决方案
您可以使用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}");
推荐阅读
- c# - 如何在 .NET Core 3.1 中使用用户名和密码获取 AWS Cognito 访问令牌?
- r - 基于列值、请求值数量的 ggraph 中弧的颜色
- pytorch - 如何限制pytorch中的参数范围?
- java - 流式操作收到错误“java.util.zip.ZipException:不正确的标头检查”
- python - 如何在 Python 中好看的列中打印单独的字符串?
- php - 为什么多对一关系定义的实体返回空结果?
- c# - MySQL - 即使结果为零也选择定义的值
- python - 为什么 Python 代码需要这么长时间才能在数据集中找到接近点?
- php - PHP 中有原生的多维、多类型排序吗?
- postgresql - 如何将显着性测试和相关性计算添加到 cube.js 流中?