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))))
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.
Is there a possible way to union these to get a result of IEnumerable(of Node)
?
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))))
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)
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.
精彩评论