📅  最后修改于: 2023-12-03 14:39:44.023000             🧑  作者: Mango
When working with lists or arrays in C#, it's often necessary to sort the elements in a specific order. One way to achieve this is through the use of a for loop and the Sort
method.
The Sort
method is used to sort the elements in a list or array in ascending order. The syntax for using this method is:
Array.Sort(array);
or
List.Sort();
where array
is the name of the array and List
is the name of the list.
Here's an example of how to use the Sort
method in a for loop:
int[] numbers = { 3, 7, 1, 9, 2, 6, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[j] < numbers[i])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
foreach (int number in numbers)
{
Console.WriteLine(number);
}
In this example, we have an array of integers called numbers
. We use a nested for loop to iterate over each element of the array and compare it to the other elements. If a smaller element is found, we swap the values using a temporary variable called temp
. Finally, we use a foreach loop to print out the sorted elements in ascending order.
Using a for loop and the Sort
method is a simple and effective way to sort lists and arrays in C#. This method can be customized to sort elements in descending order or by different criteria by using custom comparers.