0

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?

Gordon Copestake
  • 1,616
  • 4
  • 21
  • 37

1 Answers1

1

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);
}
Gordon Copestake
  • 1,616
  • 4
  • 21
  • 37
Marco
  • 22,856
  • 9
  • 75
  • 124
  • Is getPageLog better as a `List<>`? – Gordon Copestake Mar 20 '14 at 10:59
  • That depends on what you are doing. Using a List you are forcing the compiler to execute right away. Using an IEnumerable interface the execution is delayed until it is needed. There are far better explanations than mine around. See here: http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work – Marco Mar 20 '14 at 11:02