Home > Net >  Using LINQ to return an in int of how many Booleans are true within a List in a class
Using LINQ to return an in int of how many Booleans are true within a List in a class

Time:05-10

I'm wanting to learn more about LINQ however I just cannot seem to figure it out, I'm attempting to count how many people are online in an object.

        int amtOnline = 0;
        int amtOffline = 0;
        foreach(Row r in rowData.Rows)
            foreach(Profile p in r.Profiles)
                if (p.IsOnline) amtOnline  ; else amtOffline  ;

is what I'm currently using, but I'd like to use LINQ instead of a bunch of for each statements

CodePudding user response:

Personally I prefer the approach with loops as more straightforward but with LINQ one way is to flatten the nested collection and use Aggregate (and Convert.ToInt32(Boolean)):

var (amtOnline, amtOffline) = rowData.Rows
    .SelectMany(r => r.Profiles) // flatten the profiles
    .Aggregate(
        (amtOnline: 0, amtOffline: 0), // initial aggregation state using value tuple
        (agg, curr) => (agg.amtOnline   Convert.ToInt32(curr.IsOnline), agg.amtOffline   Convert.ToInt32(!curr.IsOnline))); // aggregate

Another approach is to use GroupBy on the flattened data:

var groupsDict = rowData.Rows
    .SelectMany(r => r.Profiles) // flatten the profiles
    .GroupBy(c => c.IsOnline)
    .ToDictionary(g => g.Key, g => g.Count());

var amtOnline = groupsDict.GetValueOrDefault(true);
var amtOffline = groupsDict.GetValueOrDefault(false);

CodePudding user response:

First you need to get a single collection of Profile using SelectMany, which merges multiple collections into a single collection.

Then use Count to get the count of online profiles.

var onlineCount = rows
    .SelectMany(row => row.Profiles)
    .Count(profile => profile.IsOnline);
  •  Tags:  
  • c#
  • Related