Search code examples
c#linqc#-4.0ienumerableilist

LINQ query for this scenario


I have these 2 interfaces:

public interface IShipment
{
    IEnumerable<IShippedItem> Contents { get; }
    string InvoiceNumber { get; }
}

public interface IShippedItem
{
    string ProductCode { get; }
    int Quantity { get; }
}

Now, I am trying to write a LINQ statement to get me just a list of ProductCode.

How to go about this?

IEnumerable<IShipment> shipments = GetShipments();
var productCodeList = from shipment in shipment
                      ???????

Solution

  • You can use SelectMany to flatten your contents then just use Select and get the ProductCode for each IShippedItem.

    var productCodes = shipments
                       .SelectMany(x => x.Contents)
                       .Select(x => x.ProductCode)
                       .ToList();