开发者

Join 2 lists in one

开发者 https://www.devze.com 2023-01-17 01:58 出处:网络
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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消