c# - Need better way to sum up data -


i have class

public class connectionresult {   private int connectionpercentage;    public int connectpercentage   {      { return connectionpercentage; }   }    public connectionresult(int ip)   {      // check connection , set connectionpercentage   } } 

and have manager gets several lists of connectionresult , count each value greater specific number determined configuration. implementation so:

public class currentconnections {   private static currentconnections inst;    private currentconnections()   {    }    public static currentconnections getinstance   {           {         if (inst != null)         {            inst = new currentconnections();         }         return inst;      }   }     public int countactiveconnections(params list<connectionresult>[] conns)    {      int rtval = 0;       foreach (list<connectionresult> connectionresult in conns)      {         foreach (var currconn in connectionresult)         {            if (currconn.connectpercentage > acceptable_connection)            {               rtval++;            }         }      }       return rtval;   } } 

but want make better, started write in linq , got to

conns.count(x => x.count(y => y.connectpercentage > acceptable_connection)); 

but gives me error of cannot implicitly convert type 'int' 'bool'. there way count in linq or have stay wrote? btw, i'm new linq

john skeet's answer excellent, address error you're seeing, query be:

conns.sum(x => x.count(y => y.connectpercentage > acceptable_connection)); 
  • count accepts function returns bool , returns number of items collection meet criteria.
  • sum accepts function returns int (among others), , returns sum of results of expression applied each item.

of course, whether select every item each subset , count them (like john skeet suggests), or count items each subset , add counts (like code suggests), result same.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -