C# 将元素从 IList 添加到 ObservableCollection

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2184169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:10:14  来源:igfitidea点击:

Add elements from IList to ObservableCollection

c#listobservablecollection

提问by stiank81

I have an ObservableCollection, and I'd like to set the content of an IList to this one. Now I could just create a new instance of the collection..:

我有一个 ObservableCollection,我想将 IList 的内容设置为这个。现在我可以创建集合的新实例..:

public ObservableCollection<Bar> obs = new ObservableCollection<Bar>(); 
public void Foo(IList<Bar> list)
{
    obs = new ObservableCollection<Bar>(list); 
}

But how can I actually take the content of the IList and add it to my existing ObservableCollection? Do I have to loop over all elements, or is there a better way?

但是我如何才能真正获取 IList 的内容并将其添加到我现有的 ObservableCollection 中?我是否必须遍历所有元素,还是有更好的方法?

public void Foo(IList<Bar> list)
{
   foreach (var elm in list)
       obs.Add(elm); 
}

采纳答案by Adam Ralph

You could do

你可以做

public void Foo(IList<Bar> list)
{
    list.ToList().ForEach(obs.Add);
}

or as an extension method,

或作为扩展方法,

    public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
    {
        items.ToList().ForEach(collection.Add);
    }    

回答by Richard Szalay

Looping is the only way, since there is no AddRangeequivalent for ObservableCollection.

循环是唯一的方法,因为没有AddRange等价的 for ObservableCollection

回答by RaYell

You could write your own extension method if you are using C#3+ to help you with that. This code has had some basic testing to ensure that it works:

如果您使用 C#3+ 来帮助您,您可以编写自己的扩展方法。此代码进行了一些基本测试以确保其正常工作:

public static void AddRange<T>(this ObservableCollection<T> coll, IEnumerable<T> items)
{
    foreach (var item in items)
    {
        coll.Add(item);
    }
}

回答by weston

Here is an descendant to ObservableCollection<T>to add a message efficient AddRange, plus unit tests:

这是ObservableCollection<T>添加消息高效的后代AddRange,以及单元测试:

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

ObservableCollection 不支持 AddRange 方法,所以每添加一个项目我都会收到通知,除了 INotifyCollectionChanging 呢?

回答by Greg

There is a library that solves this problem. It contains an ObservableList that can wrap a List. It can be used in the following way:

有一个库可以解决这个问题。它包含一个可以包装 List 的 ObservableList。它可以通过以下方式使用:

List<Bar> currentList = getMyList();
var obvList = new ObservableList<Bar>(currentList);

https://github.com/gsonnenf/Gstc.Collections.ObservableLists

https://github.com/gsonnenf/Gstc.Collections.ObservableLists