0

I tried doing sumlist.Add(sumlist[i] + formula3[j]) but I got the same error. I need a way to update the sum in every row. Thank you

1 Answers1

1

The first time the program executes to the statement:

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

The sumList is empty, and access to any element by index is forbidden at this time.

If the length is fixed, use Array instead of List<T> will work.

Because Array will initialize the elements.

I make some changes to your code and added some NOTE: as shown below.

Hope it works :)

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

The difference between List<T> and Array is here:

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

cg-zhou
  • 528
  • 3
  • 6