Search code examples
c#sortingobservablecollectionwindows-phone-8.1win-universal-app

Adding items to a sorted observablecollection


I have a list of items that need to be sorted by date, So what I'm doing is the following (I'm binding an ItemsControl to Pushes:

public ObservableCollection<Push> Pushes
        {
            get { return Settings.PushCol; }
            set { Settings.PushCol = value; OnPropertyChanged("Pushes"); }
        }


    Pushes = new ObservableCollection<Push>(
        Settings.PushCol
            .Where(push => push.Active == true)
            .OrderByDescending(push => push.Created)
    );

The problem here is if I were to add to Pushes, I would have to resort my Pushes using the code above, the issue this causes is that if I have a large collection it will freeze the UI until the collection has been updated.

I'm trying to find a better way to do this, can anyone advise me on what would be the best practice here?


Solution

  • First of, don't us setters for your lists. That way, you can control how items are added to your list.

    There are ways to sort items for an ObservableCollection via an CollectionViewSource. You can read about that here.

    Another solution would be to expose your list as an IEnumerable<Push>

    public IEnumerable<Push> Pushes // no Add method on IEnumerable
    {
        get { return Settings.PushCol; }
    }
    

    Then implement an Add method in your class, which controls how items are added.

    public void Add(Push p){
        int i = 0;
        for (; i < Settings.PushCol.Count; i++)
        {
            if (Settings.PushCol[i].Created > p.Created)
                break;
        }
        Settings.PushCol.Insert(i, p);
    }