按照降序排列 该如何修改
时间: 2024-04-15 11:31:52 浏览: 14
要按照降序排列,你可以在自定义的比较器中稍作修改。以下是修改后的示例代码:
```csharp
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class StringComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return string.Compare(y.Name, x.Name); // 交换了 x 和 y 的位置
}
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>()
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 20 }
};
people.Sort(new StringComparer());
foreach (var person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
```
在上述示例中,我们修改了`StringComparer`类的`Compare`方法,将比较的顺序颠倒过来。通过将`y.Name`与`x.Name`进行比较,我们实现了按照降序排列。
现在,输出结果将按照人名的降序排列。