Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a where condition on a sub table in LINQ

Tags:

.net

linq

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
like image 851
Robert Wagner Avatar asked Mar 15 '09 23:03

Robert Wagner


1 Answers

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.

like image 160
Robert Wagner Avatar answered Oct 13 '22 10:10

Robert Wagner