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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With