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

时间:2011-11-21 02:29:38

标签: 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();

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

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

4 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:3)

Student必须实施IComparable

答案 2 :(得分:3)

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

stuList.OrderBy( s => s.Name ) //.ToList if you really want a List

答案 3 :(得分: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
}