CSharp examples for LINQ:Group By
Performing group ... by ... query
using System;/*from www . ja v a 2s. co m*/ using System.Collections.Generic; using System.Linq; using System.Text; class MainClass { static void Main(string[] args) { IList<Item> datasource = createData(); Console.WriteLine("group...by... query"); // perform a query with a basic grouping IEnumerable<IGrouping<string, Item>> result = from e in datasource group e by e.Color; foreach (IGrouping<string, Item> group in result) { Console.WriteLine("\nStart of group for {0}", group.Key); foreach (Item fruit in group) { Console.WriteLine("Name: {0} Color: {1} Shelf Level: {2} days.", fruit.Name, fruit.Color, fruit.Level); } } } static IList<Item> createData() { return new List<Item>() { new Item("Oracle", "green", 7), new Item("MySQL", "MySQL", 10), new Item("C", "green", 4), new Item("fig", "brown", 12), new Item("XML", "red", 2), new Item("file", "yellow", 10), new Item("PLSQL", "red", 7) }; } } class Item { public Item(string namearg, string colorarg, int lifearg) { Name = namearg; Color = colorarg; Level = lifearg; } public string Name { get; set; } public string Color { get; set; } public int Level { get; set; } }