Search code examples
c#namedtuple

Not able to add value to List of named tuple


I have a named List of named tuple and from this function OnEndCircularReferencesCalculation()

I am trying to add value to named tuple but getting error message like : 'Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name'

Please tell me where I made the mistake in code. which line I need to change? Thanks

See my code:

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

}

Solution

  • By the way, your code could more succinctly be:

    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)));
       
    }
    
    • You don't need to ToString a string you get out of a list
    • Making the list when you make the class means you can use an auto prop
    • LINQ can turn your list of cellkey into tuple sand AddRange can consume it all in one