4

This is in response to this question in the answers section of another question.

I have a collection of Orders, each Order a collection of OrderItems, and each OrderItem has a PartId. Using LINQ how do I implement the following SQL statements:

1) Select all the orders that have a specific part ID

SELECT *
FROM Order
WHERE Id in (SELECT OrderId FROM OrderItems WHERE PartId = 100)

2) Select the Order.OrderNumber and OrderItem.PartName

SELECT Order.OrderNumber, OrderItem.PartName
FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId
WHERE OrderItem.partId = 100

3) SELECT the Order.OrderNumber and the whole OrderItem detail:

SELECT Order.OrderNumber, OrderItem.*
FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId
WHERE OrderItem.partId = 100
Community
  • 1
  • 1
Robert Wagner
  • 16,500
  • 8
  • 53
  • 71

1 Answers1

11

Actual code should be

1)

var orders = from o in Orders
             where o.OrderItems.Any(i => i.PartId == 100)
             select o;

The Any() method returns a bool and is like the SQL "in" clause. This would get all the order where there are Any OrderItems what have a PartId of 100.

2a)

// This will create a new type with the 2 details required 
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new()
                      {
                          o.OrderNumber,
                          i.PartName
                      }

The two from clauses are like an inner join.

2b)

// This  will populate the OrderItemSummary type
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new OrderItemSummary()
                      {
                          OriginalOrderNumber = o.OrderNumber,
                          PartName = i.PartName
                      }

3)

// This will create a new type with two properties, one being the
// whole OrderItem object.
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new()
                      {
                          OrderNumber = o.OrderNumber,
                          Item = i
                       }

Since "i" is an object of Type OrderItem, Item is create as an OrderItem.

Robert Wagner
  • 16,500
  • 8
  • 53
  • 71
  • 1
    Love the answers. I wonder what the syntax of "from o in Orders from i in Orders.OrderItems where i.PartId == 100" is in standard LINQ API calls (instead of that pseudo SQL syntax) – kdawg Apr 20 '11 at 19:06