【问题标题】:ERROR: Index was out of range. Must be non-negative and less than the size of the collection: sumList[i]=(sumList[i] + formula3[j]); C# [duplicate]错误:索引超出范围。必须为非负且小于集合的大小:sumList[i]=(sumList[i] + formula3[j]); C# [重复]
【发布时间】:2021-11-13 20:34:57
【问题描述】:

我尝试做sumlist.Add(sumlist[i] + formula3[j]),但我得到了同样的错误。我需要一种方法来更新每一行的总和。谢谢

【问题讨论】:

  • 好吧,作为一个错误,它只会以一种方式发生,所以.. 找出您使用大于元素数量的索引访问了哪个数组
  • 两个字:附加调试器
  • 附加调试器?不知道那是什么

标签: c# asp.net list


【解决方案1】:

程序第一次执行到语句:

sumList[i]=(sumList[i] + formula3[j]);

sumList 为空,此时禁止通过索引访问任何元素。

如果长度是固定的,使用Array 代替List<T> 会起作用。

因为Array 会初始化元素。

我对您的代码进行了一些更改并添加了一些NOTE:,如下所示。

希望它有效:)

    private List<List<double>> Formula3(List<List<double>> formula2MatrixResult, List<double> criteriaWeights)
    {
        List<List<double>> formula3List = new List<List<double>>();
        int combinations = 3;
        for (int i = 0; i < CriteriaWeights.Count; i++) //rows
        {
            List<double> formula3 = new List<double>();

            // NOTE: use an array of double instead of List<double>
            // and initialzie the length as fixed CriteriaWeights.Count
            double[] sumList = new double[CriteriaWeights.Count];

            for (int j = 0; j < combinations; j++) //col
            {
                if (formula2MatrixResult[i][j] < 0)
                    formula3.Add(0);
                else
                    formula3.Add(formula2MatrixResult[i][j] * criteriaWeights[i]);

                formula3List.Add(formula3);

                // NOTE: the List<T> count is dynamical,
                // so access element by invalid index is forbidden.
                sumList[i] = (sumList[i] + formula3[j]);
            }

            // NOTE: if you want to use List<T> finally,
            // you can call 'sumList.ToList();' to convert T[] to List<T>.
        }
        return formula3List;
    }

List&lt;T&gt;Array 的区别在这里:

Array versus List<T>: When to use which?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多