7

我有一个网页,其中有一个排序,我必须按中文笔画排序。

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

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();

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

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

4

4 回答 4

7

您需要让您的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);
    }
}
于 2011-11-21T02:43:20.040 回答
3

Student必须实施IComparable

于 2011-11-21T02:35:19.673 回答
3

而不是实现IComparable,为什么不只使用一点 LINQ?

stuList.OrderBy( s => s.Name ) //.ToList if you really want a List
于 2011-11-21T02:47:20.650 回答
0
public class Student : IComparable
{
    private string message = null;
    public Student(string message)
    {
        this.message = message;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // implement your logic, here is a example:
        if (obj != null)
            return message.CompareTo(((Student)obj).message);
        return int.MinValue;
    }

    #endregion
}
于 2011-11-21T02:42:48.947 回答