c#List排序:按中文笔划

前端之家收集整理的这篇文章主要介绍了c#List排序:按中文笔划前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个网页,其中有一种我必须通过中文笔划订购列表.

我创建了一个包含如下代码的应用程序:

  1. List<Student> stuList = new List<Student>() {
  2. new Student("上海"),new Student("深圳"),new Student("广州"),new Student("香港")
  3. };
  4. System.Globalization.CultureInfo strokCi = new System.Globalization.CultureInfo("zh-tw");
  5. System.Threading.Thread.CurrentThread.CurrentCulture = strokCi; ;
  6. //stuList.sort();

但是有一个错误:至少有一个对象必须实现IComparable.

这是什么意思,我该如何解决

解决方法

您需要让您的Student类实现IComparable接口.这需要实现一个方法CompareTo,它可以简单地返回在您尝试排序的字符串之间调用CompareTo的结果.

例如,如果构造函数初始化名称字段,则可能具有以下内容

  1. public class Student : IComparable
  2. {
  3. private string name;
  4.  
  5. public Student(string name)
  6. {
  7. this.name = name;
  8. }
  9.  
  10. public int CompareTo(object other)
  11. {
  12. Student s = other as Student;
  13. if (s == null)
  14. {
  15. throw new ArgumentException("Students can only compare with other Students");
  16. }
  17.  
  18. return this.name.CompareTo(s.name);
  19. }
  20. }

猜你在找的C&C++相关文章