开发者

Sort array\list after object is changed

开发者 https://www.devze.com 2023-01-02 11:52 出处:网络
What is the best approach for sorting a generic list when one of its objects property is changed? I have the following example to help explain what is needed.

What is the best approach for sorting a generic list when one of its objects property is changed?

I have the following example to help explain what is needed.

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 Da开发者_如何转开发teTime(2010, 6, 1);
    }
}

What is the best way to trigger a sort on the list to sort by date after the DateSent property is set? Or should I have a method to update the property and perform the sort?


You could implement IComparable<Sending> on Sending and call Sort() on the ItemsSent. I would suggest to write a method to update an object and update the list manually.

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


What you can do is you first implement INotifyChanged. Then do some thing like this;

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

So whenever a new value will set the sort method will sort the list.

0

精彩评论

暂无评论...
验证码 换一张
取 消