Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining child class lists to parent class list

Tags:

c#

linq

c#-4.0

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.

like image 578
cs0815 Avatar asked Nov 16 '12 11:11

cs0815


2 Answers

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.

like image 71
Jon Avatar answered Sep 30 '22 08:09

Jon


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();
like image 21
VMAtm Avatar answered Sep 30 '22 09:09

VMAtm