My list is:
var list = new List<int>()
{
1, 2, 3, 4
};
Without doing
int sum = list[0]*list[0] + list[1]*list[1] + list[2]*list[2] + list[3]*list[3]
My list is:
var list = new List<int>()
{
1, 2, 3, 4
};
Without doing
int sum = list[0]*list[0] + list[1]*list[1] + list[2]*list[2] + list[3]*list[3]
var result = list.Sum(o => o * o);
While the other answers work as well, you should learn how to use a loop. It is a fundamental building block of programming. For example, we can use a foreach
loop to iterate over each element in the list. see:
int sum = 0;
foreach (int val in list)
sum += val * val;