How to create a Histogram using LINQ


Let's say we have a list of records.  It doesn't matter what the types of the properties are in those records as long as they have an equality operator that the LINQ GroupBy method can take advantage of.  Let's say we have a list of employees with properties Name and Age and we want a histogram on Age of all employees.  We can write the following LINQ expression below.



var
histogram = employees.GroupBy(employee => employee.Age).Select(g => new {Key=g.Key.ToString(), Tally = g.Count()}).OrderByDescending(chartStat => chartStat.Tally).ToList();

By using GroupBy to group all similar ages and then counting the ages in each group using a Select statement we have a histogram!

Below is the full code:


using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
TestLINQHistogram
{
class Program
{
private static List<Employee> employees;
static void Main(string[] args)
{
employees =
new List<Employee>();
employees.Add(
new Employee() { Name = "Bob", Age = 30 });
employees.Add(
new Employee() { Name = "Phil", Age = 30 });
employees.Add(
new Employee() { Name = "Mary", Age = 21 });
employees.Add(
new Employee() { Name = "Jen", Age = 30 });
employees.Add(
new Employee() { Name = "Nina", Age = 22 });
employees.Add(
new Employee() { Name = "Rob", Age = 21 });
var histogram = employees.GroupBy(employee => employee.Age).Select(g => new { Key = g.Key.ToString(), Tally = g.Count() }).OrderByDescending(chartStat => chartStat.Tally).ToList();
foreach (var item in histogram)
{
Console.WriteLine("Age: {0}, Tally: {1}", item.Key, item.Tally);
}
Console.ReadLine();
}
}
}



namespace
TestLINQHistogram
{
internal class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
}

The results of running code above is shown below:

results.png