c# - 列表未使用 IComparable<T> 排序

标签 c# list sorting icomparable

这是我的抽象基类:

public abstract class BaseDataModel<T> : System.IComparable<T> where T : BaseDataModel<T>
{
    public int ID { get; set; }
    public int CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
    public int? UpdatedBy { get; set; }
    public DateTime? UpdatedOn { get; set; }


    #region IComparable<T> Members

    public virtual int CompareTo(T other)
    {
        return ID.CompareTo(other.ID);
    }

    #endregion
}

此类表示 Person 并继承自 BaseDataModel 类。

public class Person : BaseDataModel<Person>
    {
        public string Name { get; set; }
    }

但是当我尝试使用 sort() 方法对列表进行排序时,它不起作用。它返回包含 2 个对象的排序列表,但这些对象中的所有属性均为空。

    static void Main(string[] args)
    {
        List<Person> pList = new List<Person>();

        Person p = new Person();
        p.ID=2;
        p.Name="Z";
        pList.Add(p);

        Person p1 = new Person();
        p.ID = 1;
        p.Name = "A";
        pList.Add(p1);

        pList.Sort();





        Console.Read();

    }
}

这里有什么问题?

最佳答案

您正在设置 p 的属性两次;你永远不会设置 p1.ID

关于c# - 列表未使用 IComparable<T> 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333340/

相关文章:

c# - 无法反序列化 XML

c# - 开关的返回值始终为 0

Java打印列表和数组列表

python - 检查列表中的任何值是否存在于句子中

c++ - 这个特定用例的一个很好的排序算法

c++ - 按每个 vector 的大小对 C++ 中的 vector vector 进行排序

c# - 通过虚拟路径动态实例化 ASP.NET 页面类对象

c# - 使用代码验证 Microsoft Dynamics CRM

r - 使用 lapply 和 read_xls 使用文件名作为列表名称

node.js - Couchbase 查看 : get documents by keys, 已排序