.Net集合排序的一种高级玩法实例教程(2)

public class Student : IComparable<Student> { public int? Order { get; set; } public string Name { get; set; } public Class Class { get; set; } public int CompareTo(Student other) { if (ReferenceEquals(this, other)) return 0; //如果两个值的引用相同,那么直接返回相等。 if (ReferenceEquals(null, other)) return 1; //如果该实例是空的,但是传入的实例不是空的,那么返回1 //比较学校的序号 var compareResult = CompareInit(this.Class.School.Order, other.Class.School.Order); if (compareResult != 0) return compareResult; //比较班级的序号 compareResult = CompareInit(this.Class.Order, other.Class.Order); if (compareResult != 0) return compareResult; //比较学生的学号 compareResult = CompareInit(this.Order, other.Order); if (compareResult != 0) return compareResult; //如果以上还未区分出大小,比较学校的名称 compareResult = String.CompareOrdinal(this.Class.School.Name, other.Class.School.Name); if (compareResult != 0) return compareResult; //比较班级的名称 compareResult = String.CompareOrdinal(this.Class.Name, other.Class.Name); if (compareResult != 0) return compareResult; //比较学生的名称 return String.CompareOrdinal(this.Name, other.Name); }

实现该方法后,就可以对List<Student> 使用Sort方法了,我们来试试看。

using System; using System.Collections.Generic; namespace Sort { class Program { static void Main(string[] args) { var students = InitData(); students.Sort(); //此处执行了Sort方法 Console.WriteLine("Name-Order"); foreach (var student in students) { Console.WriteLine($"学校:{student.Class.School.Name}-{student.Class.School.Order}>>班级:{student.Class.Name}-{student.Class.Order}>>学生:{student.Name}-{student.Order}"); } Console.ReadLine(); } static List<Student> InitData() //创建数据 { var school1 = new School() { Order = 1, Name = "A", }; var school2 = new School { Name = "B", Order = 0 }; var class1 = new Class { Order = 1, Name = "1", School = school1, }; var class2 = new Class { Order = 2, Name = "2", School = school1, }; var class3 = new Class { Order = 1, Name = "1", School = school2, }; var student1 = new Student { Order = 1, Name = "1", Class = class1, }; var student2 = new Student { Order = 2, Name = "2", Class = class1, }; var student3 = new Student { Order = 3, Name = "3", Class = class1, }; var student4 = new Student { Order = 1, Name = "1", Class = class2, }; var student5 = new Student { Order = 1, Name = "1", Class = class3, }; return new List<Student> { student5, student3, student4, student2, student1 }; } } }

执行效果如下:

.Net集合排序的一种高级玩法实例教程

 

可以看到,学校B虽然是以B开头,但是因为期Order为0比1更靠前,所以以Order为准,学校B排到了最前面。

好几天没写了,写博客对我我而言,意义无非在于加深印象同时把我所掌握的东西分享给大家,这个方法是今天同事教我的,可能对园子里大神来说这比较基础,但是相信如果掌握这个方法,对以后也许中复杂排序会有比较有用,希望对大家也能有所帮助。

项目的GitHub地址:

https://github.com/liuzhenyulive/Sort (本地下载)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdsxsx.html