Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How to create a Histogram using LINQ
WhatsApp
Mike Gold
14y
26.3
k
0
0
25
Blog
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
Up Next
How To Create Pagination Using LINQ In C#
Ebook Download
View all
Printing in C# Made Easy
Read by 22.3k people
Download Now!
Learn
View all
Membership not found