联盟2的ObservableCollection名单 [英] Union two ObservableCollection Lists

查看:77
本文介绍了联盟2的ObservableCollection名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个的ObservableCollection名单,我想团结起来。我幼稚的方法是使用联盟 - 方法:

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的类型的ObservableCollection太多。但是编译器会因这条线以下错误:

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

键入System.Collections.Generic.IEnumerable不能转换隐为System.Collections.ObjectModel.ObservableCollection。一个explicite转换已经存在。 (也许转换丢失)

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).

任何人事先知道,如何合并双方ObservableCollections,并得到一个ObservableCollection的结果呢?

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

谢谢,
弗兰克

Thanks in advance, Frank

伊迪丝说:我刚刚意识到,必须提及的是我开发一个Silverlight 3的应用程序,因为类的ObservableCollection在SL3和.NET3.0的不同是非常重要的场景。

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.

推荐答案

在LINQ 联盟扩展方法返回一个IEnumerable。您需要列举每个项目添加到结果集: -

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);

如果你想要一个ToObservableCollection那么你可以这样做:

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;
    }
 }

现在您的线路是:

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

这篇关于联盟2的ObservableCollection名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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