'Using LINQ to return an in int of how many Booleans are true within a List in a class
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
Solution 1:[1]
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);
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | hijinxbassist |
