sort a list of numbers in csharp

To sort a list of numbers in C#, you can use the Sort() method from the List<T> class. Here's an example:

main.cs
List<int> numbers = new List<int> { 5, 2, 10, 8, 1 };
numbers.Sort();
70 chars
3 lines

After calling Sort(), numbers will be sorted in ascending order: { 1, 2, 5, 8, 10 }.

If you need to sort in descending order, you can use the Reverse() method after calling Sort():

main.cs
numbers.Sort();
numbers.Reverse();
35 chars
3 lines

Now numbers will be sorted in descending order: { 10, 8, 5, 2, 1 }.

If you need more control over the sorting algorithm, you can use the Sort(Comparison<T> comparison) method, which takes a delegate that defines the comparison logic. For example, to sort in descending order based on the absolute value:

main.cs
numbers.Sort((x, y) => Math.Abs(y).CompareTo(Math.Abs(x)));
60 chars
2 lines

Now numbers will be sorted in descending order based on the absolute value: { 10, 8, 5, 2, 1 }.

gistlibby LogSnag