Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0427 Sort

We can use Linq to sort generic collections and arrays. using System; using System.Collections; using System.Collections.Generic; using System.Linq; class MainClass { public static void Main() { // Create a new array and populate it. int[] array = { 4, 2, 9, 3 }; // Created a new, sorted array array = Enumerable.OrderBy(array, e => e).ToArray<int>(); // Display the contents of the sorted array. foreach (int i in array) { Console.WriteLine(i); } } } The output: 2 3 4 9 Sort a list using System; using System.Collections; using System.Collections.Generic; using System.Linq; class MainClass { public static void Main() { // Create a list and populate it. List<string> list = new List<string>(); list.Add("M"); list.Add("K"); list.Add("A"); list.Add("A"); // Enumerate the sorted contents of the list. Console.WriteLine("\nList sorted by content"); foreach (string person in Enumerable.OrderBy(list, e => e)) { Console.WriteLine(person); } // Sort and enumerate based on a property. Console.WriteLine("\nList sorted by length property"); foreach (string person in Enumerable.OrderBy(list, e => e.Length)) { Console.WriteLine(person); } } } The output: List sorted by content A A K M List sorted by length property M K A A