Reputation: 1647
Is there a simple way to show a percentage of the total within a Linq GroupBy
?
I currently have:
private static object GetPageUsers(IEnumerable<Pagehit> getPageLog)
{
return getPageLog
.GroupBy(g => g.UserID)
.Select(x => new { User = GetUserFName(x.Key.ToString()),
NumberOfHits = x.Count(),
percentage = x.Count() / total
})
.OrderByDescending(o => o.NumberOfHits);
}
In this line percentage = x.Count() / total
how do I get the total?
Upvotes: 0
Views: 101
Reputation: 23937
getPageLog is an IEnumerable, so it has no Count property. But it should have a Count()
extension method.
You could get it using:
private static object GetPageUsers(IEnumerable<Pagehit> getPageLog)
{
return getPageLog
.GroupBy(g => g.UserID)
.Select(x => new { User = GetUserFName(x.Key.ToString()),
NumberOfHits = x.Count(),
percentage = (100 * x.Count()) / getPageLog.Count() + "%"
})
.OrderByDescending(o => o.NumberOfHits);
}
Upvotes: 1