Search code examples
c#listelementdivide

Is that possible to divide all elements in C# double list to that double list elements sum (which makes total = 1)


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);