Union two ObservableCollection Lists

杀马特。学长 韩版系。学妹 提交于 2020-01-12 05:18:05

问题


I have two ObservableCollection lists, that i want to unite. My naive approach was to use the Union - Method:

ObservableCollection<Point> unitedPoints = observableCollection1.Union(observableCollection2);

ObservableCollection1/2 are of type ObservableCollection too. But the Compiler throws the following error for this line:

The Type "System.Collections.Generic.IEnumerable" can't be converted implicit to "System.Collections.ObjectModel.ObservableCollection". An explicite conversion already exists. (Maybe a conversion is missing)

(wording may not be exact, as I translated it from german).

Anyone knows, how to merge both ObservableCollections and get an ObservableCollection as result?

Thanks in advance, Frank

Edith says: I just realized that it is important to mention that I develop a Silverlight-3-Application, because the class "ObservableCollection" differ in SL3 and .NET3.0 scenarios.


回答1:


The LINQ Union extension method returns an IEnumerable. You will need to enumerate and add each item to the result collection:-

var unitedPoints = new ObservableCollection<Point> ();
foreach (var p in observableCollection1.Union(observableCollection2))
   unitedPoints.Add(p);

If you'd like a ToObservableCollection then you can do:

public static class MyEnumerable
{
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
    {
        var result = new ObservableCollection<T> ();
        foreach (var item in source)
           result.Add(item);
        return result;
    }
 }

Now your line is:

var unitedPoints = observableCollection1.Union(observableCollection2).ToObservableCollection();



回答2:


Do you want to merge the existing contents, but then basically have independent lists? If so, that's relatively easy:

ObservableCollection<Point> unitedPoints = new ObservableCollection<Point>
    (observableCollection1.Union(observableCollection2).ToList());

However, if you want one observable collection which is effectively a "view" on others, I'm not sure the best way to do that...



来源:https://stackoverflow.com/questions/1565289/union-two-observablecollection-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!