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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With