Vishal
Vishal

Reputation: 12369

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

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 ?

Upvotes: 4

Views: 12325

Answers (5)

Douglas Flores
Douglas Flores

Reputation: 110

Best way to do it:

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

or

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

Upvotes: 1

toddmo
toddmo

Reputation: 22416

If You

  • want to do it in one line
  • don't want to maintain an extension method
  • can't take advantage of list.Sum() because your list data isn't 1s and 0s

you can do something like this:

percentAchieved = (int)
                  ((double)(from MyClass myClass
                  in myList
                  where MyClass.SomeProperty == "SomeValue"
                  select myClass).ToList().Count / 
                  (double)myList.Count * 
                  100.0
                  );

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128307

If you're working with any ICollection<T> (such as List<T>) the Count property will probably be O(1); but in the more general case of any sequence the Count() extension method is going to be O(N), making it less than ideal. Thus for the most general case you might consider something like this which counts elements matching a specified predicate and all elements in one go:

public static double Percent<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    int total = 0;
    int count = 0;

    foreach (T item in source)
    {
        ++count;
        if (predicate(item))
        {
            total += 1;
        }
    }

    return (100.0 * total) / count;
}

Then you'd just do:

var list = new List<int> { 1, 1, 0, 0, 0 };
double percent = list.Percent(i => i == 1);

Output:

40

Upvotes: 6

MartinStettner
MartinStettner

Reputation: 29174

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;

Upvotes: 12

BrokenGlass
BrokenGlass

Reputation: 160912

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

var list = new List<int> {1,1,0,0,0};
double percent = list.Average() * 100;

Upvotes: 6

Related Questions