I don't know if I'm asking this the right way but here's what I want to do:
Model
public abstract class IncomingOrderBase
{
public string Summary { get; set; }
}
public class IncomingProductOrder : IncomingOrderBase
{
public Product Product { get; set; }
}
public class IncomingServiceOrder : IncomingOrderBase
{
public Service Service { get; set; }
}
public class Sale
{
public ICollection<IncomingProductOrder> ProductOrders { get; set; }
public ICollection<IncomingServiceOrder> ServiceOrders { get; set; }
public List<IncomingOrderBase> GetAllOrders()
{
var orders = this.ProductOrders +++PLUS+++ this.ServicesOrders;
return orders.ToList();
}
}
Usage
foreach(var order in sale.GetAllOrders())
{
Console.WriteLine(order.GetType().Name);
//output = "ProductOrder" or "ServiceOrder" not "IncomingOrderBase"
}
How do I compile the two (or more) lists into one list and then get the original (derived) type from the resulting list? I think I had it working using Concat()
but I would really appreciate an expert's example on this.
Yes, Concat
is what you want:
public List<IncomingOrderBase> GetAllOrders()
{
return ProductOrders.Concat<IncomingOrderBase>(ServicesOrders).ToList();
}
Note that this will only work on .NET 4, which has generic covariance for IEnumerable<T>
. If you're using .NET 3.5, you need
public List<IncomingOrderBase> GetAllOrders()
{
return ProductOrders.Cast<IncomingOrderBase>()
.Concat(ServicesOrders.Cast<IncomingOrderBase>())
.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