sort a list in csharp

To sort a list in C#, you can use the List.Sort() method. The Sort() method can sort the elements in a list in ascending or descending order based on the comparison logic you provide.

Here's an example that sorts a list of integers in ascending order:

main.cs
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };
numbers.Sort(); // Sort in ascending order
foreach (int num in numbers)
{
    Console.WriteLine(num);
}
157 chars
7 lines

Output:

main.cs
1
2
5
8
9
10 chars
6 lines

You can also sort a list in descending order by providing a custom comparison function that compares the elements in reverse order. Here's an example:

main.cs
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };
numbers.Sort((x, y) => y.CompareTo(x)); // Sort in descending order
foreach (int num in numbers)
{
    Console.WriteLine(num);
}
182 chars
7 lines

Output:

main.cs
9
8
5
2
1
10 chars
6 lines

related categories

gistlibby LogSnag