Passhero
Passhero

Reputation: 23

How to write this code using the Linq Extension Method-Syntax?

I have these following classes from an Linq Example:

public class Customer
{
    public Customer();

    public Cities City { get; set; }
    public string Name { get; set; }
    public Order[] Orders { get; set; }
}

public class Product
{
    public Product();

    public double Price { get; set; }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

public class Order
{
    public Order();

    public int OrderID { get; set; }
    public int ProductID { get; set; }
    public int Quantity { get; set; }
    public bool Shipped { get; set; }
}

static void Main(string[] args)
{
    var allOrders = from cust in customers
                    from ord in cust.Orders
                    join prod in products on ord.ProductID equals prod.ProductID
                    select new
                    {
                        cust.Name,
                        ord.ProductID,
                        OrderAmount = ord.Quantity * prod.Price
                    };
}

I want to create the same collection (Name, ProductID, Orderamount) with the linq Extension Method Syntax. My problem is that I don't know how to realize the two datasources from cust in customers from ord in cust.Orders in the Extension Method Syntax. Does anyone have any idea how it could work?

I got this but I have no access to the `CustomerName in the collection.

var allOrders2 =
    customers.SelectMany(cust => cust.Orders)
             .Join(products,
                   ord => ord.ProductID,
                   prod => prod.ProductID,
                   (ord, prod) => new
                   {
                       ord.ProductID,
                       OrderAmount = ord.Quantity * prod.Price
                   });

Upvotes: 2

Views: 100

Answers (1)

CompuChip
CompuChip

Reputation: 9232

If you order does not refer back to a customer, the trick is to first create a dataset which keeps the customers and orders linked together:

customers
   .SelectMany(c => c.Orders.Select(o => new {
       cust = c,
       ord = o
   }))

Then on this CustomerOrder (co) you can apply your join:

...
    .Join(products, 
        co => co.ord.ProductID, 
        prod => prod.ProductID, 
        (co,prod) => new {
          co.cust.Name,
          co.ord.ProductID, 
          OrderAmount = ord.Quantity * prod.Price});

Upvotes: 3

Related Questions