我有一个 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.
因此,理想情况下,我希望一次插入整个项目范围,这意味着只对底层列表进行一次随机播放,并希望有一个 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").
Collection<T> 没有公开任何执行此操作的方法.ListInsertRange(),但是 IListCollectionItems 属性没有.
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.
有没有办法做到这一点?
Is there any way at all to do this?
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
车牌检测有哪些好的算法?What are good algorithms for vehicle license plate detection?(车牌检测有哪些好的算法?)
Unity中图像的onClick事件onClick event for Image in Unity(Unity中图像的onClick事件)
运行总 C#Running Total C#(运行总 C#)
单击带有 JAvascript.ASP.NET C# 的超链接时删除目录Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(单击带有 JAvascript.ASP.NET C# 的超链接时删除目录)
asp.net listview 在单击时突出显示行asp.net listview highlight row on click(asp.net listview 在单击时突出显示行)
从函数调用按钮 OnClickCalling A Button OnClick from a function(从函数调用按钮 OnClick)