简体   繁体   English

列表未使用IComparable排序<T>

[英]list is not getting sorted using IComparable<T>

This is my abstract base class: 这是我的抽象基类:

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
}

This class represents Person and imherits from the BaseDataModel class. 此类表示Person及其继承自BaseDataModel的类。

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

But when i am trying to sort the List using sort() method, it doesnt work. 但是,当我尝试使用sort()方法对列表进行排序时,它不起作用。 It returns the sorted list with 2 objects but all the properties in those objects are null. 它返回包含2个对象的排序列表,但这些对象中的所有属性均为null。

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

    }
}

What is the problem here? 这里有什么问题?

You're setting the properties of p twice; 您要设置p的属性两次; you never set p1.ID . 您永远不会设置p1.ID

The problem is here: 问题在这里:

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

This should be: 应该是:

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

    Person p1 = new Person();
    // Change properties of p1, not p!
    p1.ID = 1;
    p1.Name = "A";
    pList.Add(p1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM