TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to create a Histogram using LINQ
Mike Gold
Nov 10, 2010
25.9
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
LINQ provides a quick and easy way to generate a histogram from your data. Here's how
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:
How to create a Histogram using LINQ
Next Recommended Reading
How To Create Pagination Using LINQ In C#