19 January, 2010
0 Comments
0 categories
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 { [TestFixture] public class IntegrationTester { [Test] [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)); } } } }
Result
Group[Item 1] ItemCount[1]
Group[Item 2] ItemCount[2]
Group[Item 3] ItemCount[2]
Group[Item 4] ItemCount[1]