How to count items per category with LINQ

If you want to count items per category with LINQ in C#, you can use:

public static void CountItemsPerCategory()
        {
            List<string> items = new List<string>();
            items.Add("Item 1");
            items.Add("Item 2");
            items.Add("Item 3");
            items.Add("Item 4");
            items.Add("Item 2");
            items.Add("Item 3");

            var result = from i in items
                         group i by i into g
                         select new { Group = g.Key, ItemCount = g.Count() };

            foreach (var test in result)
            {
                Console.WriteLine(string.Format("Group [ {0} ] ItemCount [ {1} ]", test.Group, test.ItemCount));
            }
        }
Output

How to count items per category with LINQ How to count items per category with LINQ Reviewed by Bhaumik Patel on 1:08 AM Rating: 5