Friday, June 28, 2013

Fast AddRange method for ObservableCollection


public class ObservableCollectionEx : ObservableCollection
{
    public void AddRange(IEnumerable<T> list)
    {
        foreach (T item in list)
        {
            this.Items.Add(item);
        }

        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    public void ClearAndAddRange(IEnumerable<T> list)
    {
        this.Items.Clear();

        this.AddRange(list);
    }
}

2 comments:

  1. How is this better? Doesn't each call to Items.Add(item) also cause a notification? How does this code eliminate any notifications or make things any faster?

    ReplyDelete
  2. How is this better? Doesn't each call to Items.Add(item) also cause a notification? How does this code eliminate any notifications or make things any faster?

    ReplyDelete