tags:

views:

33

answers:

1

I am new in .NET > 2

I have

List<Dog> dogs;
List<Cat> cats;
List<Animal> animals;

I need to join dogs and cats in animals.

I know that there should be a elegant way to do it using LINQ or stuff from .NET 4, isn't it?

My Initial variant:

animals.AddRange(dogs);
animals.AddRange(cats);
+4  A: 

.NET 4 makes this relatively easy using generic covariance, yes - although you need to be explicit:

animals = dogs.Concat<Animal>(cats).ToList();

Alternatively:

animals = dogs.Cast<Animal>().Concat(cats).ToList();

or:

IEnumerable<Animal> dogsAsAnimals = dogs;
animals = dogsAsAnimals.Concat(cats).ToList();

Prior to .NET 4, you could use:

animals = dogs.Cast<Animal>().Concat(cats.Cast<Animal>()).ToList();

Basically the difference with .NET 4 is that there's an implicit conversion from IEnumerable<Cat> to IEnumerable<Animal>. For lots more detail, see Eric Lippert's blog.

Jon Skeet
Is it possible to use LINQ in this situation?
serhio
@serhio: That *is* using LINQ. `Concat`, `Cast` and `ToList` are parts of LINQ.
Jon Skeet
@Jon: cool :"); ...however, I see two `AddRange` more "readable" that `dogs.Cast<Animal>().Concat(cats).ToList();`
serhio