对象更改后对array \ list进行排序

时间:2010-06-04 08:55:44

标签: c# .net-2.0

当更改其某个对象属性时,对通用列表进行排序的最佳方法是什么?

我有以下示例来帮助解释所需的内容。

public class Sending
{
    public Sending(int id, DateTime dateSent)
    {
        this.Id = id;
        this.DateSent = dateSent;
    }

    public int Id { get; set; }
    public DateTime DateSent { get; set; }
}

public class Operation
{
    public List<Sending> ItemsSent = new List<Sending>();

    public Operation()
    {
        ItemsSent.Add(new Sending(1, new DateTime(2010, 6, 2)));
        ItemsSent.Add(new Sending(2, new DateTime(2010, 6, 3)));

        ItemsSent[1].DateSent = new DateTime(2010, 6, 1);
    }
}

在设置DateSent属性后触发列表排序以按日期排序的最佳方法是什么?或者我应该有一个方法来更新属性并执行排序?

2 个答案:

答案 0 :(得分:1)

您可以在IComparable<Sending>上实施Sending并在Sort()上致电ItemsSent。我建议写一个方法来更新对象并手动更新列表。

public class Sending: IComparable<Sending>
{
  // ...
  public int CompareTo(Sending other)
  {
    return other == null ? 1 : DateSent.CompareTo(other.DateSend);  
  }
}

答案 1 :(得分:0)

您可以做的是首先实现INotifyChanged。 然后做这样的事情;

public class Sending : INotifyChanged
{
    private int id;
    private DateTime dateSent;

    public Sending(int id, DateTime dateSent)
    {
        this.Id = id;
        this.DateSent = dateSent;
    }

    public int Id { get; set; }
    public DateTime DateSent 
     {
       get
         {
            return this.dateSend;
         }
      set
         {
           this.dateSent = value;
           OnPropertyChangerd("DateSent");
           //CallYou List<Sending> Sort method;
         }
}

因此,只要设置了新值,sort方法就会对列表进行排序。

相关问题