有效地向ObservableCollection添加一系列值 [英] Adding a range of values to an ObservableCollection efficiently

查看:1378
本文介绍了有效地向ObservableCollection添加一系列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ObservableCollection 的项目绑定到我的视图中的列表控件。

I have an ObservableCollection of items that is bound to a list control in my view.

一种情况,我需要添加一大块的值到集合的开始。
Collection< T> .Insert 文档将每个插入指定为O(n)操作,每个插入还生成 CollectionChanged 通知。

I have a situation where I need to add a chunk of values to the start of the collection. Collection<T>.Insert documentation specifies each insert as an O(n) operation, and each insert also generates a CollectionChanged notification.

因此,我理想地希望插入整个范围的项目在一个移动,意味着只有一个shuffle的底层列表,并希望一个 CollectionChanged 通知(可能是重置)。

Therefore I would ideally like to insert the whole range of items in one move, meaning only one shuffle of the underlying list, and hopefully one CollectionChanged notification (presumably a "reset").

集合< T& code>不公开任何方法这样做。 列表< T> InsertRange(),但 IList< T> 集合< T> 通过 Items 属性展示。

Collection<T> does not expose any method for doing this. List<T> has InsertRange(), but IList<T>, that Collection<T> exposes via its Items property does not.

这有什么办法吗?

推荐答案

ObservableCollection暴露一个受保护的 Items 属性,它是没有通知语义的基础集合。这意味着你可以通过继承ObservableCollection创建一个你想要的集合:

The ObservableCollection exposes an protected Items property which is the underlying collection without the notification semantics. This means you can build a collection that does what you want by inheriting ObservableCollection:

class RangeEnabledObservableCollection<T> : ObservableCollection<T>
{
    public void InsertRange(IEnumerable<T> items) 
    {
        this.CheckReentrancy();
        foreach(var item in items)
            this.Items.Add(item);
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

用法:

void Main()
{
    var collection = new RangeEnabledObservableCollection<int>();
    collection.CollectionChanged += (s,e) => Console.WriteLine("Collection changed");
    collection.InsertRange(Enumerable.Range(0,100));
    Console.WriteLine("Collection contains {0} items.", collection.Count);  
}

这篇关于有效地向ObservableCollection添加一系列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆