7

Imagine a doube list like the follow

List<double> lstDouble=new List<double>{4,6,2,7,1,1};

So what i want is dividing all elements in this list to sum of the elements(21).

So the list becomes after dividing :

lstDouble = {4/21,6/21,2/21,7/21,1/21,1/21}

Which would mean that the new sum of the elements = 1

I can do that via iteration etc but i wonder are there any short way since Matlab has. And my assistant professor keep telling me that learn Matlab and use it but i don't want :D I love C#

Thank you.

C# 4.0 WPF application

Joshua Scott
  • 645
  • 5
  • 9
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342

5 Answers5

12
var sum = lstDouble.Sum();
var result = lstDouble.Select(d => d / sum);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
4

You can do this with LINQ:

var sum = lstDouble.Sum();
var newLst = lstDouble.Select( x => x/sum );
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
2

Use a lambda expression:

 lstDouble.ForEach(x => x = x/21);
Eugene Feingold
  • 279
  • 2
  • 5
2
var sum = lstDouble.Sum();
var result = lstDouble.Select(v => v / sum);
RobIII
  • 8,488
  • 2
  • 43
  • 93
  • @CodeInChaos Yeah, thought of that just after I posted. Corrected. Now I have the same answer as everybody else here :-) – RobIII Apr 05 '12 at 00:04
0

This is a pseudo code:

double sum = 0;
for(int i=0; i<array.length; i++)
   sum+=array[i];
for(int i=0; i<array.length; i++)
   array[i]=array[i]/sum;
kasavbere
  • 5,873
  • 14
  • 49
  • 72
  • down vote is supposed to mean the code would not work. So why the negative vote? – kasavbere Apr 05 '12 at 00:02
  • even that does not warrant a down vote. The poster could figure it out from there. – kasavbere Apr 05 '12 at 00:06
  • 2
    downvote means the answer is "not useful". the question states "I can do that via iteration", which is what this answer is doing, which makes this answer not useful in the context of the question. – Ethan Brown Apr 05 '12 at 00:15