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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;

namespace Ada.Cdf.Test
  public class IntegrationTester
    [Explicit("Not a unittest")]
    public void Test()
      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));



Group[Item 1] ItemCount[1]

Group[Item 2] ItemCount[2]

Group[Item 3] ItemCount[2]

Group[Item 4] ItemCount[1]



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.