kleineg
kleineg

Reputation: 491

How to get the union of two sets of objects that inherit from a common class

Say I have two classes, Plane and Car, which both inherit from Vehicle

public class Vehicle
{
}

public class Car : Vehicle
{
}

public class Plane : Vehicle
{
}

How do I take a list of planes and a list of cars and union them into a single list of vehicles? I tried the following, but there was an error on cars saying the best overload has to take a receiver of type IEnumerable

List<Vehicle> vehicles = cars.Union(planes);

Is there an easier way of doing this than using two .Select loops to cast all the objects to Vehicle?

Upvotes: 2

Views: 436

Answers (1)

InBetween
InBetween

Reputation: 32750

You need to cast the enumeration to the common base type:

var vehicles = cars.Cast<Vehcile>().Union(planes);

The reason bieng that Union's signature is the following:

Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)

In your code, form first the compiler reasons out that TSource is Car, and therefore second has the wrong type; IEnumerable<Plane> instead of the expected IEnumerable<Car>.

Bear in mind that in type inference the compiler won't bactrack and try something else if inference goes wrong, that is, it wont do the following:

  1. first is IEnumerable<Car>, so TSource could be Car.
  2. second is not IEnumerable<Car>, so TSource can not be Car.
  3. Is there a common type TSource so that both IEnumerable<Car> and IEnumerable<Plane> can be implicitly converted to IEnumerable<TSource>? Yes, Vehicle, therefore TSource is Vehicle.

Upvotes: 5

Related Questions