C# Sort排序
2023-06-13 09:12:31 时间
大家好,又见面了,我是你们的朋友全栈君。
List 的Sort方法排序有三种结果 1,0,-1分别表示大于,等于,小于。
1.对于数值类型的List (List<int>),直接使用Sort进行排序。
List<int> scoreList=new List<int>(){89,100,78,23,67};
scoreList.Sort();//默认按升序排列,相当于:scoreList.Sort((x,y)=>x.CompareTo(y))
scoreList.Sort((x,y)=>-x.CompareTo(y));//降序排列
2.对于非数值类型或者自定义类型,可通过实现IComparable接口重写CompareTo方法来排序:
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
//ComparetTo:大于 1; 等于 0; 小于 -1;
public int CompareTo(Person p)
{
int result;
if (this.Name == p.Name && this.Age == p.Age)
{
result = 0;
}
else
{
//this.Name表示后面的 Mary p.Name表示前面的 Bob
//Mary 跟Bob 由小到大比较,如果Mary 与 Bob 比较 大于0(说明Mary 大于Bob),则 result=1(说明是由小到大的顺序)
if (this.Name.CompareTo(p.Name) > 0)//先按名字小到大排列
{
result = 1;
}
else if (this.Name == p.Name && this.Age > p.Age)//名字相同则按年龄由小到大排列
{
result = 1;
}
else
{
result = -1;
}
}
return result;
}
public override string ToString()
{
return this.Name + "-" + this.Age;
}
}
List<Person> lstPerson = new List<Person>();
lstPerson.Add(new Person() { Name = "Bob", Age = 19 });
lstPerson.Add(new Person() { Name = "Mary", Age = 18 });
lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
lstPerson.Add(new Person() { Name = "Lily", Age = 20 });
lstPerson.Sort();
foreach (Person item in lstPerson)
{
Console.WriteLine(item.ToString());
}
Console.ReadKey();
输出:Bob-19 Lily-20 Mary-17 Mary-18 或不实现IComparable接口而使用linq排序:
List<Person> lstPerson = new List<Person>();
lstPerson.Add(new Person() { Name = "Bob", Age = 19 });
lstPerson.Add(new Person() { Name = "Mary", Age = 18 });
lstPerson.Add(new Person() { Name = "Mary", Age = 17 });
lstPerson.Add(new Person() { Name = "Lily", Age = 20 });
lstPerson.Sort();
lstPerson.Sort((x, y) => {
int result;
if (x.Name == y.Name && x.Age == y.Age)
{
result = 0;
}
else
{
if (x.Name.CompareTo(y.Name) > 0)
{
result = 1;
}
else if (x.Name == y.Name && x.Age > y.Age)
{
result = 1;
}
else
{
result = -1;
}
}
return result;
});
foreach (Person item in lstPerson)
{
Console.WriteLine(item.ToString());
}
Console.ReadKey();
输出:Bob-19 Lily-20 Mary-17 Mary-18
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159784.html原文链接:https://javaforall.cn
相关文章
- c#FileStream文件读写.以及filestream,file和FileInfo的区别
- c# 多线程并发-金三银四面试:C#.NET面试题高级篇2-多线程
- C#几种排序算法
- c#n个数排序实现代码
- C#排序算法之快速排序
- 基于jquery的分页控件(C#)
- JavaScript打开word文档的实现代码(c#)
- C#拼接SQL语句用ROW_NUMBER实现的高效分页排序
- c#递归访问文件夹(删掉歌词文件)
- C#数据结构与算法揭秘二线性结构
- 怎么利用c#修改services的Startuptype
- C#对DataTable里数据排序的方法
- c#测试本机sql运算速度的代码示例分享
- 浅谈C#设计模式之开放封闭原则
- C#应用XML作为数据库的快速开发框架实现方法
- C#中this指针的用法示例
- C#实现Datatable排序的方法