📅  最后修改于: 2023-12-03 15:08:52.596000             🧑  作者: Mango
在C#中,可以使用Array类提供的Sort()方法对数组进行排序。该方法可以排序各种类型的数组,例如整数,字符串等等。以下是如何使用Array.Sort()方法对数组进行排序的示例。
以下是Array.Sort()方法的语法:
public static void Sort(Array array);
public static void Sort(Array array, IComparer comparer);
public static void Sort(Array array, int index, int length);
public static void Sort(Array array, int index, int length, IComparer comparer);
以下示例演示如何使用Array.Sort()方法对整数数组进行排序:
using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 2, 8, 7, 1 };
Array.Sort(numbers);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.ReadKey();
}
}
输出:
1
2
5
7
8
以下示例演示如何使用Array.Sort()方法对字符串数组进行排序:
using System;
class Program
{
static void Main(string[] args)
{
string[] names = { "apple", "orange", "banana", "peach" };
Array.Sort(names);
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.ReadKey();
}
}
输出:
apple
banana
orange
peach
以下示例演示如何使用Array.Sort()方法对自定义对象进行排序:
using System;
class Program
{
static void Main(string[] args)
{
Person[] people = { new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 20) };
Array.Sort(people);
foreach (Person person in people)
{
Console.WriteLine("{0} ({1})", person.Name, person.Age);
}
Console.ReadKey();
}
}
class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public int CompareTo(Person other)
{
return this.Age.CompareTo(other.Age);
}
}
输出:
Charlie (20)
Alice (25)
Bob (30)
除了使用对象自身的CompareTo()方法进行排序外,我们还可以使用IComparer
using System;
class Program
{
static void Main(string[] args)
{
Person[] people = { new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 20) };
Array.Sort(people, new PersonComparer());
foreach (Person person in people)
{
Console.WriteLine("{0} ({1})", person.Name, person.Age);
}
Console.ReadKey();
}
}
class PersonComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
输出:
Alice (25)
Bob (30)
Charlie (20)
以上就是在C#中使用Array.Sort()方法对数组进行排序的示例。您可以使用该方法轻松对各种数组类型进行排序。