我有一个命名元组的命名列表,从这个函数中

我试图为命名的元组添加值,但收到错误消息,如:'Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name'

请告诉我代码中的错误在哪里.我需要换哪一行?谢谢

查看我的代码:

private class CustomCalculationService : ICustomCalculationService
{
    private List<(string sheet, int rowindex, int columnindex)>  _ListOfCells;
    public List<string>? Sheets { get; set; }
    public List<(string sheet, int rowindex, int columnindex)>? ListOfCells { get { return _ListOfCells; } }
    
    public void OnEndCircularReferencesCalculation(IList<CellKey> cellKeys)
    {
        if (cellKeys.Count > 0)
        {
            if (_ListOfCells == null)
                _ListOfCells = new List<(string sheet, int rowindex, int columnindex)>();

            for (int r = 0; r <= cellKeys.Count - 1; r++)
            {
                _ListOfCells.Add((Sheets[cellKeys[r].SheetId].ToString(), cellKeys[r].RowIndex, cellKeys[r].ColumnIndex));
            }
        }
    }

}

推荐答案

顺便说一句,你的代码可以更简洁:

private class CustomCalculationService : ICustomCalculationService
{ 
    public List<string>? Sheets { get; set; }
    public List<(string sheet, int rowindex, int columnindex)>? ListOfCells { get; } = new();
    
    public void OnEndCircularReferencesCalculation(IList<CellKey> cellKeys) =>
      ListOfCells.AddRange(cellKeys.Select(ck => (Sheets[ck.SheetId], ck.RowIndex, ck.ColumnIndex)));
   
}
  • 你不需要从列表中提取字符串
  • 当你制作这个课程时,列出这个列表意味着你可以使用自动props
  • LINQ可以将你的cellkey列表转换为元组,AddRange可以一次将其全部消耗掉

Csharp相关问答推荐

将修剪声明放入LINQ中

在命令行中使用时安装,但在单击时不会安装

使用LayoutKind在C#中嵌套 struct .显式

. net依赖注入如何避免服务类中的新

Int和uint相乘得到LONG?

自动映射程序在GroupBy之后使用项目

如何在NET 8最小API中自动记录TypedResults.Stream响应

未在数据流块之间传播完成

什么时候接受(等待)信号灯?尽可能的本地化?

在使用UserManager时,如何包含与其他实体的关系?

如何从另一个类的列表中按ID取值

MudBlazor Textfield已禁用,但其验证工作正常

如何在.NET MAUI中最大化GraphicsView的大小?

在C#中,当输入一个方法/局部函数时,我的IEnumerator被重置/重新创建.为什么?

在构造函数中传递C#函数以用作EventHandler委托的订阅服务器

Foreach非常慢的C#

WPF:如何从DatagridHeader的内容模板绑定到词典项

.NET6最小API:操作.MapGet之后的响应

如何在C#Visual Studio IF语句中删除换行符

从route获取URL参数,无需指定@page route - Blazor