对于某个集合,我们需要对其按对象不同属性进行排序,对于在查询数据时遇到这样的情况,一些sql语句就能解决,当然我们也可以把数据查出来自己经过循环判断之后也能实现,今天这里介绍一种比较简单的方法,在定义对象时,只需要实现IComparable接口,去重写一下里面的CompareTo方法就可以了,如果希望有更强大的功能,可以参考我以前写的http://zxlyecf2.iteye.com/blog/1977948;对于习惯使用Linq的实现起来就跟简单了
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CustomListTest.Students { public class Student : IComparable<Student> { public Student(string n, string g, int i) { name = n; gender = g; id = i; } public string name { get; set; } public string gender { get; set; } public int id { get; set; } public int CompareTo(Student other) { //name降序,id升序,若要改变顺序只需修改一下other.name和name的前后顺序 if (other.name.CompareTo(name) == 0) { return id.CompareTo(other.id); } else { return other.name.CompareTo(name); } } } }
Student songchao = new Student("SongChao", "Man", 100150); Student wuxing = new Student("WuXing", "Women", 100121); Student songchao2 = new Student("SongChao", "Women", 100130); Student aa = new Student("aa", "Women", 100133); Student aa2 = new Student("aa", "Women", 100130); List<Student> students = new List<Student>(); students.Add(songchao); students.Add(wuxing); students.Add(songchao2); students.Add(aa); students.Add(aa2); foreach (Student student in students) { Console.WriteLine("Name " + student.name + " ID " + student.id); } Console.WriteLine(""); students.Sort(); foreach (Student student in students) { Console.WriteLine("Name " + student.name + " ID " + student.id); } 使用Linq更简单实现 //var ss = from u in students orderby u.name descending, u.id ascending select u; //foreach (Student student in ss) //{ // Console.WriteLine("Name " + student.name + " ID " + student.id); //} Console.Read();