score:11

Accepted answer

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;

score:0

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

score:1

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;

score:5

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

score:6

in this special case you can also use average() :

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

Related Query

More Query from same tag