C#集合排序的三种方法(List<T>.Sort、LINQ 的 OrderBy、IComparable<T> 接口)
见过不少人、经过不少事、也吃过不少苦,感悟世事无常、人心多变,靠着回忆将往事串珠成链,聊聊感情、谈谈发展,我慢慢写、你一点一点看......
1、使用 List<T>.Sort
方法与自定义比较器
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class PersonComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
// 按年龄升序排序
return x.Age.CompareTo(y.Age);
// 或更复杂的排序逻辑
}
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "A", Age = 15 },
new Person { Name = "B", Age = 25 },
new Person { Name = "C", Age = 35 }
};
people.Sort(new PersonComparer());
foreach (var person in people)
{
Console.WriteLine($"{person.Name}, {person.Age}");
}
}
}
2、使用 LINQ 的 OrderBy
方法与自定义键选择器
var people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
}; var sortedPeople = people.OrderBy(p => p.Age).ToList(); //var sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.Name}, {person.Age}");
}
3、默认的排序顺序
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person other)
{
if (other == null) return 1;
return this.Age.CompareTo(other.Age);
}
}
// 然后可以直接使用 Sort 方法,不需要传递比较器
people.Sort();
关注我,不失联。有啥问题请留言。
感情恋爱合集https://blog.csdn.net/forever8341/category_12863789.html
职业发展故事https://blog.csdn.net/forever8341/category_12863790.html
常用代码片段https://blog.csdn.net/forever8341/category_12863793.html
程序开发教程https://blog.csdn.net/forever8341/category_12863792.html
自我备考经验 https://blog.csdn.net/forever8341/category_12863791.html
高阶高效代码https://blog.csdn.net/forever8341/category_12873345.html
金融语言解析https://blog.csdn.net/forever8341/category_12877262.html