RangeObservableCollection – Pragmatic Implementation

This implementation improves the behaviour of the standard ObservableCollection when dealing with a large number of elements. This collection does not fire an event for each inserted element, but fires a reset event when adding elements

    public class RangeObservableCollection<T> : ObservableCollection<T>
    {
        private static readonly NotifyCollectionChangedEventArgs ResetChangedArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
        private static readonly PropertyChangedEventArgs CountChangedEventArgs = new PropertyChangedEventArgs("Count");
        private static readonly PropertyChangedEventArgs ItemChangedEventArgs = new PropertyChangedEventArgs("Item[]");
 
        public RangeObservableCollection(IEnumerable<T> items)
            : base(items)
        {
        }
 
        public RangeObservableCollection(List<T> list)
            : base(list)
        {
        }
 
        public RangeObservableCollection()
        {
        }
 
        public void RemoveRange(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
 
            foreach (T item in list)
            {
                Items.Remove(item);
            }
 
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void AddRange(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
 
            foreach (T item in list)
            {
                Items.Add(item);
            }
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void RemoveAll()
        {
            Items.Clear();
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void ReplaceAll(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
            Items.Clear();
            this.AddRange(list);
        }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: