Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0422 ThenBy

Input: IOrderedEnumerable<TSource> Lambda expression: TSource => TKey Append a ThenBy operator: 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<string> query = names.OrderBy(s => s.Length).ThenBy(s => s); foreach (String s in query) { Console.WriteLine(s); } } } The output: C C# C++ CSS SQL HTML Java Oracle Python Javascript The following sorts first by length, then by the second character, and finally by the first character: 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" }; names.OrderBy(s => s.Length).ThenBy(s => s[1]).ThenBy(s => s[0]); foreach (String s in names) { Console.WriteLine(s); } } } The output: Java C# Javascript SQL Oracle Python C++ C HTML CSS