Reputation: 11577
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
Upvotes: 7
Views: 222
Reputation:
return conns.SelectMany(x=> x).Where(conn => conn.ConnectPercentage > ACCEPTABLE_CONNECTION).;
Upvotes: 0
Reputation: 149020
John Skeet's answer is excellent, but to address the error that you're seeing, the query would be:
conns.Sum(x => x.Count(y => y.ConnectPercentage > ACCEPTABLE_CONNECTION));
Count
accepts a function which returns bool
and returns the number of items from the collection which meet that criteria. Sum
accepts a function which returns int
(among others), and returns the sum of the results of the expression applied to each item.Of course, whether you select every item from each subset and then count them up (like John Skeet suggests), or you count the items from each subset and then add up the counts (like my code suggests), the result will be exactly the same.
Upvotes: 6
Reputation: 1500575
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.
Upvotes: 7