C# Sort排序
来源:互联网 发布:java.util.zip 加密 编辑:程序博客网 时间:2024/05/18 02: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
0 0
- C# 排序 List.Sort
- C# List排序Sort
- C#中的 sort排序
- C# Sort排序
- C# list sort 排序
- C# List Sort 排序
- C# Array.sort排序
- C# List<T>.Sort排序
- C#中List的排序用法(Sort)
- C# List Sort 按照名称升序排序
- C#中List的排序用法(Sort)
- C#中List的排序用法(Sort)
- C# List.Sort()自定义比较方法排序
- C#中List的排序用法(Sort)
- C#中List的排序(Sort)
- c#的DataTable.DefaultView.Sort 排序方法
- C#中List的排序(Sort)
- C# 利用list.sort()进行排序
- C++中的构造函数
- mapReduce概念及用法
- MDWIKI
- dubbo服务者配置说明
- Android中的异步任务
- C# Sort排序
- STL-Intelligent IME
- POJ 3164 Command Network(最小树形图)
- 条件随机场CRF HMM,MEMM的比较
- Introducing Android Instant Apps
- iOS app打包 -- 生成ipa测试包 步骤详解
- Mybatis_java项目
- 协同开发时, 如何合并不稳定的联调代码?
- 一个90%程序员写不对的算法——二分查找