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);
.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.
精彩评论