Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0402 GroupBy

Input: IEnumerable<TSource> Lambda expression: TSource => TKey using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] names = { "Java", "C#", "Javascript", "SQL", "Oracle", "Python", "C++", "C", "HTML", "CSS" }; IEnumerable< IGrouping<int,string>> grouping = names.GroupBy(s => s.Length); foreach (IGrouping<int, string> group in grouping) { Console.WriteLine("Key: " + group.Key); foreach (string filename in group) Console.WriteLine(" - " + filename); } } } The output: Key: 4 - Java - HTML Key: 2 - C# Key: 10 - Javascript Key: 3 - SQL - C++ - CSS Key: 6 - Oracle - Python Key: 1 - C