-4

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]
Backs
  • 24,430
  • 5
  • 58
  • 85
Marcel Pirlog
  • 69
  • 2
  • 10
  • 1
    Possible duplicate of [C# List of objects, how do I get the sum of a property](https://stackoverflow.com/questions/4351876/c-sharp-list-of-objects-how-do-i-get-the-sum-of-a-property) – Ghonima Apr 23 '19 at 17:35
  • Hello, Could you add what you have tried so far? What is the exact expected result? – John Mercier Apr 23 '19 at 20:55

2 Answers2

2
var result = list.Sum(o => o * o);
Lews Therin
  • 3,707
  • 2
  • 27
  • 53
Backs
  • 24,430
  • 5
  • 58
  • 85
  • 1
    do you mind explaining your answer, the OP may not have an idea what it is even doing let alone know anything about `linq` and or lambda expressions, thanks! – Trevor Apr 23 '19 at 17:31
1

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;
Lews Therin
  • 3,707
  • 2
  • 27
  • 53
JamieT
  • 1,177
  • 1
  • 9
  • 19