c#List <T>排序:按中文笔划

Tod*_*hao 7 c# list stroke

我有一个网页,其中有一种我必须通过中文笔划订购列表.

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

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();
Run Code Online (Sandbox Code Playgroud)

但是有一个错误: At least one object must implement IComparable.

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

Pla*_*ure 8

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

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)