CSharp examples for LINQ:Group By
Grouping products by category
using System;//from w w w .j a va2 s . com using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var products = new List<Product> { new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M }, new Product { Name = "XML", OnHand = 300, UnitCost = 1.15M }, new Product { Name = "MySQL", OnHand = 0, UnitCost = 2.00M }, new Product { Name = "Whatsit", OnHand = 1, UnitCost = 1000.0M }, new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M }, new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M }, new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M }, new Product { Name = "XML", OnHand = 300, UnitCost = 1.15M } }; var categories = from p in products group p by p.Name into tempGrp select new { Name = tempGrp.Key, Products = tempGrp }; foreach (var productGroup in categories) { Console.WriteLine("\tLevel '{0}':", productGroup.Name); foreach (var prod in productGroup.Products) { Console.WriteLine("\t\t{0}", prod.Name); } } } } class Product { public string Name; public int OnHand; public decimal UnitCost; }