tags:

views:

34

answers:

2

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 DateTime(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?

+1  A: 

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);  
  }
}
Jason
Thanks Jason, this might be the approach that I use. Would you advise making the collection readonly so that it can't be added to? Otherwise there would be a scenario when the list may not be sorted.
Sammy T
A: 

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.

Johnny
Is the interface INotifyPropertyChanged? Wouldn't this mean that I would have to override the "Add" method of the list and assign an event for every object added to the collection so that the sort method can be fired? Or am I implementing it incorrectly?
Sammy T
If I didn't get you wrong then suppose you want to sort the list whenever your datesent property is changed or added then you don't have to do any thing extra.
Johnny