Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need better way to sum up data

Tags:

c#

linq

i have this class

public class ConnectionResult
{
  private int connectionPercentage;

  public int ConnectPercentage
  {
     get { return connectionPercentage; }
  }

  public ConnectionResult(int ip)
  {
     // Check connection and set connectionPercentage
  }
}

and i have a manager that gets several lists of ConnectionResult and count each value greater then a specific number determined by configuration. my implementation is so:

public class CurrentConnections
{
  private static CurrentConnections inst;

  private CurrentConnections()
  {

  }

  public static CurrentConnections GetInstance
  {
     get
     {
        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 i want to make it better, so i started to write it in linq and i got to

conns.Count(x => x.Count(y => y.ConnectPercentage > ACCEPTABLE_CONNECTION));

but this gives me an error of Cannot implicitly convert type 'int' to 'bool'. is there a way to count it in linq or do i have to stay with what i wrote? btw, i'm new to linq

like image 903
No Idea For Name Avatar asked Jul 18 '13 12:07

No Idea For Name


1 Answers

You're using Count twice, and I don't think you want to. I think you just want:

return conns.SelectMany(list => list)
            .Count(conn => conn.ConnectPercentage > ACCEPTABLE_CONNECTION);

The SelectMany call is to flatten the "array of lists" into a single sequence of connections.

like image 75
Jon Skeet Avatar answered Oct 19 '22 22:10

Jon Skeet