c# List<T> 排序 : by Chinese strokes

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

但出现错误:至少一个对象必须实现 IComparable。

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

最佳答案

您需要让您的Student 类实现IComparable 接口(interface)。这需要实现一个方法 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);
    }
}

关于c# List<T> 排序 : by Chinese strokes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8206644/

相关文章:

c# - F# 中的度量单位 "Type"

c# - 在数组中使用 Person 类

Python:从列表列表中删除元组

java - ArrayList<Number> 是什么意思?

text - 为什么 CGContextSetRGBStrokeColor 不适用于 ios7?

graphics - 减少脂肪中风

fabricjs - Fabric JS 中自定义图像的描边

c# - WPF:同步 ItemsControl 中所有项目的宽度

c# - 无法加载配置文件 web.config - 正在被另一个进程使用

c - typedef 用法不清楚