Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Polymorphic Lists into One List and Get Derived Type

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.

like image 696
Benjamin Avatar asked Dec 22 '22 01:12

Benjamin


1 Answers

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();
}
like image 113
Jon Skeet Avatar answered Dec 23 '22 14:12

Jon Skeet