具有相同基类的LINQ Union对象 [英] LINQ Union objects with same Base Class

查看:47
本文介绍了具有相同基类的LINQ Union对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Union从多个对象列表中创建所有对象的列表.

I'm trying to create a list of all my objects from several lists of objects using Union.

Return Chart.AnnotativeNodes.Union( _
         Chart.DecisionNodes.Union( _
           Chart.EndNodes.Union( _
             Chart.StartNodes.Union(Chart.WorkCenterNodes))))

由于无法将List(of AnnotativeNode)List(of DecisionNode)合并,因此上一行出现错误.每个列表的定义类似于List(of EndNode)List(of StartNode),但是每个类都继承自基本类型Node.

The above line gets an error because I can't union List(of AnnotativeNode) with List(of DecisionNode). Each list defined like List(of EndNode) or List(of StartNode), but each class inherits from the base type Node.

是否有可能将它们结合起来以获得IEnumerable(of Node)的结果?

Is there a possible way to union these to get a result of IEnumerable(of Node)?

推荐答案

如果您使用的是.NET 4,则应该可以这样做:

If you're using .NET 4, you should be able to do it like this:

Return Chart.AnnotativeNodes.Union(Of Node) _
           (Chart.DecisionNodes.Union(Of Node) _
               (Chart.EndNodes.Union(Of Node) _
                   (Chart.StartNodes.Union(Of Node)(Chart.WorkCenterNodes))))

由于.NET 4中的通用协方差,因此该方法应该起作用.否则,您可以在每个集合上调用Cast(Of Node).

That should work due to generic covariance in .NET 4. Otherwise, you could just call Cast(Of Node) on each of the collections.

我怀疑您的代码可以更可读地编写,例如:

I suspect your code can be written more readably though, as:

Return Chart.AnnotativeNodes.Union(Of Node)(Chart.DecisionNodes) _
                            .Union(Of Node)(Chart.EndNodes) _
                            .Union(Of Node)(Chart.StartNodes) _
                            .Union(Of Node)(Chart.WorkCenterNodes)

如果您需要以特定顺序进行合并,则可以将其弄乱-我没有打扰,因为Union首先是设置操作.

If you need the union-ing to happen in a particular order, you can mess with it - I haven't bothered, as Union is meant to be a set operation in the first place.

这篇关于具有相同基类的LINQ Union对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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