Is that possible to divide all elements in C# double list to that double list elements sum (which makes total = 1)
Question
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
Solution
var sum = lstDouble.Sum();
var result = lstDouble.Select(d => d / sum);
OTHER TIPS
You can do this with LINQ:
var sum = lstDouble.Sum();
var newLst = lstDouble.Select( x => x/sum );
Use a lambda expression:
lstDouble.ForEach(x => x = x/21);
var sum = lstDouble.Sum();
var result = lstDouble.Select(v => v / sum);
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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow