c# - "System.ArgumentOutOfRangeException"为什么会显示?为什么 list<>number 停止打印?

标签 c# .net linq foreach

当我执行它时,它会在 8 处停止打印并显示

"System.ArgumentOutOfRangeException"

List<int> number = new List<int> { 1, 2, 2, 5, 4, 8, 6};
number.ForEach(delegate (int i) { Console.WriteLine(number[i]); });
Console.ReadKey();

最佳答案

正如@tkausl已经提到的,ForEach传递给你的是值,而不是索引,实际上不建议使用List.ForEach,但如果你仍然想这样做使用它,你可以做这样的事情:

 number.ForEach(c => { Console.WriteLine(c); });

您可以像这样简单地使用foreach:

foreach (var c in number)
{
   Console.WriteLine(c);
}

您可以在这里找到讨论:foreach vs someList.ForEach(){}

关于c# - "System.ArgumentOutOfRangeException"为什么会显示?为什么 list<>number 停止打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60990271/

相关文章:

c# - 无效操作异常 : Cannot consume scoped service 'Microsoft.JSInterop.IJSRuntime' from singleton '...IAuthentication' in Blazor

c# - Foreach 更改未保留在 Linq 项目集合中

c# - 流利的断言 : Approximately compare the properties of objects stored in Lists

c# - 当要滚动的项目太多时,Windows 窗体列表框会溢出

c# - 使用 Linq 从数组构建字典

c# - 在 Winform 中的 datagridview 底部添加新行

c# - Linq 从 List<List<int>> 中获取包含最多元素和其元素内部最大差异的 List

c# - C#使用异步方法进行模型

c# - 使用 LINQ 创建类似面包屑的层次结构

c# - 获取从 StartDate 到 EndDate 的日期列表