Wednesday, October 29, 2008

Use LINQ to count items in a List

I wanted a way to go through a list of items and get a count for each distinct item in the list.
To do this nice and easy, I just use LINQ.

class Program
{
static void Main()
{
var cities = new List<string>
{
"Sydney",
"Perth",
"Sydney",
"Melbourne",
"Brisbane",
"Melbourne",
"Sydney"
};

var result = (from c in cities
group c by c into grouping
orderby grouping.Key ascending
select new {grouping.Key, Count = grouping.Count()});

foreach (var item in result)
{
Console.WriteLine(string.Format("City={0}, Count={1}", item.Key, item.Count));
}

Console.ReadLine();
}
}

Count items in a List using LINQ

Please let me know if this helps you.