C# 数组排序
来源:互联网 发布:下载苹果软件 编辑:程序博客网 时间:2024/05/16 19:26
如果要直接调用C#数组的Sort()方法对数组进行排序(如:Array.Short();list.Short().....),则必须要存储在数组中的对象实现IComparable或IComparable<T>接口,并实现CompareTo方法来指定用于排序的字段。比如实现了IComparable接口的System.String类就可以直接进行排序:
string[] strs={"aaa","cccc","bbbb"};Array.Short(strs);如果要实现对数据实体对象的排序,则需要自己实现IComparable或IComparable<T>接口:
public class Student :IComparable { public int Age { get; set; } public string Name { get; set; } public int Score { get; set; } /// <summary> /// 实现IComparable接口,用Age做比较 /// </summary> /// <param name="obj">比较对象</param> /// <returns>比较结果</returns> public int CompareTo(object obj) { if (obj is Student) { return Age.CompareTo(((Student)obj).Age); } return 1; } }
默认的我们可以调用:
List<Student> mouses = new List< Student > ();mouses.Short();这样默认的就会按照Age字段值来排序。如果你需要用来排序的字段不确定,可以向Short()方法传入委托参数Comparison<T>:
mouses.Sort(delegate(Student a, Student b) { return a.Age.CompareTo(b.Age); });委托的拉姆达形式(等效于上面的委托)这个方式灵活又方便,想对哪个字段排序就对哪个字段排序:
mouses.Sort ((m1, m2) => m1.Name.CompareTo (m2.Name));//mouses.Sort ((Mouse x, Mouse y) => x.Name.CompareTo (y));还可以实现泛型接口IComparer<T>:
<span style="color:#111111;">using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompare{ class StudentCompare :IComparer<Student> { public int Compare(Student a, Student b) { return a.Age.CompareTo(b.Age); } }}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompare{ class Program { static void Main(string[] args) { List<Student> students = new List<Student>(); students.Add(new Student("001","kenshincui",25)); students.Add(new Student("002", "miaoer", 23)); students.Add(new Student("003", "shenjinjuan", 22)); students.Add(new Student("004", "nieyanxin", 24)); Console.WriteLine("未进行排序之前:"); foreach (Student st in students) { Console.WriteLine(st.No+","+st.Name+","+st.Age+";"); } Console.WriteLine("List.Sort (泛型 IComparer) 排序之后:"); </span><span style="color:#ff0000;">students.Sort(new StudentCompare());</span><span style="color:#111111;"> foreach (Student st in students) { Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";"); } Console.ReadKey(); } }}</span>冒泡排序:
int temp = 0; for (int i = list.Count; i > 0; i--) { for (int j = 0; j < i - 1; j++) { if (list[j] > list[j + 1]) { temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } }
0 0
- C#数组排序
- c#数组排序
- C#中的数组排序
- C#数组排序
- C#数组排序问题
- c# 数组排序
- C#数组随机排序
- C#数组排序
- C#数组排序
- C# 数组排序
- C# 数组排序
- c#数组排序
- C#数组冒泡排序
- C#关于数组排序
- C#对象数组排序方法
- C#数组查找与排序
- C#对象数组排序方法
- C#数组查找与排序
- QT5.2中新建lib库,在引用时出现error LNK2019: 无法解析的外部符号错误
- hdu 4336 概率dp + 状压
- Swift学习笔记(十五)——程序员浪漫之用Swift+Unicode说我爱你
- dubbo总结(1)——关于我和dubbo
- poj 2777 Count Color(线段树、状态压缩、位运算)
- C# 数组排序
- Android Handler 异步消息处理机制的妙用 创建强大的图片加载类
- 免费真实增加网站访问量的方法
- hdoj1106排序
- [LeetCode] Majority Element II
- windows和linux中UDP编程
- 偶数求和
- 关于mysql Table * is read only错误
- AssertValid和Dump函数的应用