Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way in linq to calculate the percentage from a list?

Tags:

c#

linq

I have a list of 1s and 0s and I have to now calculate the percent meaning if 1 he achieved it else he doesn't. So e.g -

{1,1,0,0,0}

So for e.g If List has 5 items and he got 2 ones then his percent is 40%. Is there a function or way in LINQ I could do it easily maybe in one line ? I am sure LINQ experts have a suave way of doing it ?

like image 975
Vishal Avatar asked Nov 28 '22 18:11

Vishal


2 Answers

What about

var list = new List<int>{1,1,0,0,0};
var percentage = ((double)list.Sum())/list.Count*100;

or if you want to get the percentage of a specific element

var percentage = ((double)list.Count(i=>i==1))/list.Count*100;

EDIT

Note BrokenGlass's solution and use the Average extension method for the first case as in

var percentage = list.Average() * 100;
like image 93
MartinStettner Avatar answered Dec 10 '22 13:12

MartinStettner


In this special case you can also use Average() :

var list = new List<int> {1,1,0,0,0};
double percent = list.Average() * 100;
like image 40
BrokenGlass Avatar answered Dec 10 '22 13:12

BrokenGlass