SkyeBoniwell
SkyeBoniwell

Reputation: 7102

Combining 2 IEnumerables of different types with common interface

I have created this interface to use as a combined collection for 2 other collections.

Both of my objects(ourCars and ourTrucks) contain info about my collection of cars and my collection of trucks.

However the fields are not the same, I so I want to create a new collection in which to combine the two.

Private Interface carTruckCombo
    Property ID As String  
    Property make As String 
    Property model As String 
End Interface

Dim cars As IEnumerable(Of ourCars) = Enumerable.Empty(Of ourCars)()
Dim trucks As IEnumerable(Of ourTrucks) = Enumerable.Empty(Of ourTrucks)()

Now this is where I get stuck...what do I do now?

Dim combinedResults As IEnumerable(Of carTruckCombo)

Upvotes: 3

Views: 250

Answers (3)

Joel Coehoorn
Joel Coehoorn

Reputation: 415860

First of all, you need to make sure that both your ourCars and ourTrucks types Implement the new carTruckCombo type. When that is done, you can use code like this:

Dim combinedResults = cars.Cast(Of carTruckCombo).Concat(trucks.Cast(Of carTruckCombo))

Upvotes: 5

L.B
L.B

Reputation: 116138

var combinedResults  = 
    cars.Select(c=>new carTruckCombo{ID=c.ID,make=c.make,model=c.model})
    .Union(tracks.Select(t=>new carTruckCombo{ID=t.ID,make=t.make,model=t.model}));

Upvotes: 4

Stan R.
Stan R.

Reputation: 16065

You can use the Concat method, HOWEVER (please read before downvote :) ) you are trying to combine 2 seperate types into one collection and unless they both inherit from the same base class then you cannot do Concat.

You might consider creating a base class called Vehicle and then derive ourCars and ourTrucks from this class.

Otherwise you have to transform both of your collections to the same type using a Select method.

C#:

combinedResults =  cars.Concat(trucks);

Upvotes: 3

Related Questions