C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This program will populate the List with 3 strings, and sort them alphabetically. We can use the same method for integral types.
Important: The Sort method does not copy the List and sort the copy. It modifies the existing list.
C# program that uses Sort
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> list = new List<string>();
list.Add("tuna");
list.Add("velvetfish");
list.Add("angler");
// Sort fish alphabetically, in ascending order (A - Z)
list.Sort();
foreach (string value in list)
{
Console.WriteLine(value);
}
}
}
Output
angler
tuna
velvetfish
IEnumerable: LINQ works on IEnumerable collections, which include List. This syntax is confusing at first, but makes sense.
IEnumerableContextual: The orderby keyword is called a contextual keyword, and in this place it means to order the List elements by their lengths.
Ascending: You can specify "ascending" or "descending", such as with "orderby element.Length ascending".
orderbyascending, descendingC# program that sorts with LINQ
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> list = new List<string>();
list.Add("mississippi"); // Longest.
list.Add("indus");
list.Add("danube");
list.Add("nile"); // Shortest.
var lengths = from element in list
orderby element.Length
select element;
foreach (string value in lengths)
{
Console.WriteLine(value);
}
}
}
Output
nile
indus
danube
mississippi
Tip: We use a Comparison lambda to handle more complex sorting orders. Here we sort on the first digit of a number.
Note: For your program, you will want to modify the right-hand part of the lambda inside the Sort method call.
Also: To sort in reverse order, we can compare the second argument "b" to the first "a" instead of the opposite order.
Names: The names "a" and "b" are not important for the lambda. We can use identifiers like "left" and "right" instead.
C# program that uses Sort, lambda expression
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
numbers.Add(4);
numbers.Add(0);
numbers.Add(10);
numbers.Add(50);
numbers.Add(1000);
numbers.Add(40);
// ... Sort the numbers by their first digit.
// We use ToString on each number.
// We access the first character of the string and compare that.
// This uses a lambda expression.
numbers.Sort((a, b) => (a.ToString()[0].CompareTo(b.ToString()[0])));
Console.WriteLine(":::SORTED BY FIRST DIGIT:::");
foreach (var result in numbers)
{
Console.WriteLine(result);
}
}
}
Output
:::SORTED BY FIRST DIGIT:::
0
10
1000
4
40
50