加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#List排序:按中文笔划

发布时间:2020-12-16 04:57:17 所属栏目:百科 来源:网络整理
导读:我有一个网页,其中有一种我必须通过中文笔划订购列表. 我创建了一个包含如下代码的应用程序: ListStudent stuList = new ListStudent() { new Student("上海"),new Student("深圳"),new Student("广州"),new Student("香港") }; System.Globalization.Cultu
我有一个网页,其中有一种我必须通过中文笔划订购列表.

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

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

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

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

解决方法

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

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

public class Student : IComparable
{
    private string name;

    public Student(string name)
    {
        this.name = name;
    }

    public int CompareTo(object other)
    {
        Student s = other as Student;
        if (s == null)
        {
            throw new ArgumentException("Students can only compare with other Students");
        }

        return this.name.CompareTo(s.name);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读