c#中listsort排序-创新互联
1、List.Sort (泛型 Comparison) 法
创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站制作、成都网站建设、外贸营销网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的噶尔网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!此方法的参数是Comparison类型,其实是一个包含两个参数的委托,因此使用此方法,我们只需要定义一个委托,其两个参数均为Student类型,在委托实现的方法比较两个Student对象的Age属性即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class Program { static void Main(string[] args) { Liststudents = new List (); 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 (泛型 Comparison) 排序之后:"); students.Sort(delegate(Student a, Student b) { return a.Age.CompareTo(b.Age); }); foreach (Student st in students) { Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";"); } Console.ReadKey(); } } }
2、List.Sort (泛型 IComparer)
此方法需要一个泛型IComparer接口类型,因此只要定义一个类实现此接口然后再调用此方法即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class StudentCompare :IComparer{ 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 students = new List (); 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) 排序之后:"); students.Sort(new StudentCompare()); foreach (Student st in students) { Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";"); } Console.ReadKey(); } } }
参考资料: c#中list排序 http://www.studyofnet.com/news/531.html
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
分享文章:c#中listsort排序-创新互联
当前URL:http://hbruida.cn/article/csgjjo.html