哪个.Net集合一次添加多个对象并收到通知? [英] Which .Net collection for adding multiple objects at once and getting notified?

查看:189
本文介绍了哪个.Net集合一次添加多个对象并收到通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在考虑 System.Collections.ObjectModel ObservableCollection< T> 类。这很奇怪,因为

Was considering the System.Collections.ObjectModel ObservableCollection<T> class. This one is strange because


  • 它有一个添加方法,只接受一个项。无AddRange或等效项。

  • 通知事件参数具有NewItems属性,它是 IList (对象.. not T)

  • it has an Add Method which takes one item only. No AddRange or equivalent.
  • the Notification event arguments has a NewItems property, which is a IList (of objects.. not T)

我需要在这里添加一批对象到集合,监听器也获得批处理作为通知的一部分。我缺少一些东西与ObservableCollection?是否有另一个类符合我的规范?

My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?

更新:不要尽可能地卷起我自己。我必须建立添加/删除/更改等等。很多东西。

Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.

相关Q:

http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each

推荐答案

看来, INotifyCollectionChanged 接口允许在添加多个项目时进行更新,肯定为什么 ObservableCollection< T> 没有 AddRange 。您可以为 AddRange 创建一个扩展方法,但这将导致添加的每个项目的事件。如果这不可接受,您应该能够继承 ObservableCollection< T> 如下:

It seems that the INotifyCollectionChanged interface allows for updating when multiple items were added, so I'm not sure why ObservableCollection<T> doesn't have an AddRange. You could make an extension method for AddRange, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from ObservableCollection<T> as follows:

public class MyObservableCollection<T> : ObservableCollection<T>
{
    // matching constructors ...

    bool isInAddRange = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        // intercept this when it gets called inside the AddRange method.
        if (!isInAddRange) 
            base.OnCollectionChanged(e);
    }


    public void AddRange(IEnumerable<T> items)
    {
         isInAddRange = true;
         foreach (T item in items)
            Add(item);
         isInAddRange = false;

         var e = new NotifyCollectionChangedEventArgs(
             NotifyCollectionChangedAction.Add,
             items.ToList());
         base.OnCollectionChanged(e);
    }
}

这篇关于哪个.Net集合一次添加多个对象并收到通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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