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
Asked
Active
Viewed 171 times
0

chicacherry
- 25
- 5
-
2Well, as an error it only happens one way, so.. find out which one of your arrays you've accessed using an index that is larger than the number of elements – Caius Jard Nov 13 '21 at 20:36
-
two words: attached debugger – user2864740 Nov 13 '21 at 21:15
-
attached debugger? not sure what that is – chicacherry Nov 14 '21 at 19:41
1 Answers
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:

cg-zhou
- 528
- 3
- 6