cs0815
cs0815

Reputation: 17388

Combining child class lists to parent class list

I have a parent class X and two lists of child classes X1 and X2 (X1 and X2 derive from X). Is there an easy way to combine the lists of X1 and X2 into a list of Xs?
I could loop over the lists of X1 and X2 and add then to the list of X but this seems a bit cumbersome.

Upvotes: 5

Views: 1805

Answers (2)

VMAtm
VMAtm

Reputation: 28345

Use Enumerable.Cast Method, like this:

var list1 = new List<X1>();
var list2 = new List<X2>();
var result = list1.Cast<X>().Concat(list2.Cast<X>()).ToList();

Upvotes: 2

Jon
Jon

Reputation: 437366

LINQ can do this conveniently with

var both = list1.Cast<X>().Concat(list2.Cast<X>()).ToList();

or with

var both = ((IEnumerable<X>)list1).Concat((IEnumerable<X>)list2).ToList();

but it's looping nonetheless -- just under the covers.

Upvotes: 6

Related Questions