以下是一个示例代码,演示了如何按名称对对象属性列表进行排序:
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
List persons = new List
{
new Person {Name = "John", Age = 25},
new Person {Name = "Alice", Age = 30},
new Person {Name = "Bob", Age = 20}
};
Console.WriteLine("Before sorting:");
foreach (Person person in persons)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
persons.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
Console.WriteLine("After sorting:");
foreach (Person person in persons)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
这段代码首先定义了一个Person
类,该类包含名称和年龄属性。然后,在Main
方法中创建了一个List
,并向其中添加了几个Person
对象。
在排序之前,我们使用foreach
循环遍历列表,并打印每个Person
对象的名称和年龄。
然后,使用Sort
方法对persons
列表进行排序。在排序方法中传递了一个比较器,该比较器使用string.Compare
方法按照名称对两个Person
对象进行比较。
最后,在排序之后,再次使用foreach
循环遍历列表,并打印每个Person
对象的名称和年龄,以验证排序结果。
运行该代码,你将看到输出结果如下:
Before sorting:
Name: John, Age: 25
Name: Alice, Age: 30
Name: Bob, Age: 20
After sorting:
Name: Alice, Age: 30
Name: Bob, Age: 20
Name: John, Age: 25
可以看到,列表已按照名称进行了排序。
上一篇:按名称对导出类型进行分组
下一篇:按名称对对象数组排序错误