-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
  • 23,679
  • 4
  • 50
  • 77
Marcel Pirlog
  • 59
  • 2
  • 9
  • 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

1
var result = list.Sum(o => o * o);
Lews Therin
  • 3,579
  • 2
  • 25
  • 51
Backs
  • 23,679
  • 4
  • 50
  • 77
  • 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,579
  • 2
  • 25
  • 51
JamieT
  • 1,177
  • 8
  • 19