## Pages

### Counting Value Frequency with LINQ (code snippet)

This post is a code snippet: a short code example to demonstrate a topic.

From now on I’ll write in this blog useful code snippets that I come to write.

A question on StackOverflow motivated me to write a simple C# console application that demonstrates a way of counting how often a value appears within a given set. I used LINQ to accomplish this.

I’ve commented the code in green so that it’s easier to understand what’s going on.

```using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
// Creating a list of Values that serves as the data source for LINQ query.
List<int> values = new List<int>()
{
0, 1, 2, 3, 6, 2, 3, 1, 0, 4, 5, 7, 8, 9, 3, 7, 5
};

// For each Value in the data source, let's group by Value into g. g stores all Values grouped.
// Using the select new constructor we create an Anonymous Type that has each distinct Value and its Count (how often it appears).
var query = from v in values
group v by v into g
select new { Value = g.Key, Count = g.Count() };

// A simple foreach that prints in the screen each Value and its frequency.
foreach (var v in query)
{
Console.WriteLine("Value = {0}, Count = {1}", v.Value, v.Count);
}
}
}```

This is the output:

```Value = 0, Count = 2
Value = 1, Count = 2
Value = 2, Count = 2
Value = 3, Count = 3
Value = 6, Count = 1
Value = 4, Count = 1
Value = 5, Count = 2
Value = 7, Count = 2
Value = 8, Count = 1
Value = 9, Count = 1```

Hope you enjoy and make good use of this code.

Feel free to comment and add any other way of doing this in a more efficient or elegant fashion.