LINQ中基于外表的选择查询
我的 LINQ to SQL dbml 文件中有 2 个表、OrderDetails 和 Requests 。 OrderDetailsID 是请求表中的外键。
我想编写查询以根据 OrderId 从 OrderDetails 获取 UnitCost 总和。 如果请求表中每个 OrderDetailsID 都有一行,并且 Requests.Last.RequestType="Refund" 我想从主金额中减少总退款金额,否则如果没有基于 OrderDetailsID 的行,则添加到总和中。
这是我实现该方法的方法。 我希望防止使用“对于每个”。
有什么解决方案吗?
iRefund = (From od1 In dc.OrderDetails _
Where od1.OrderID =1 _
Select od1.UnitCost).Sum
Dim objOrderDetails = (From od1 In dc.OrderDetails _
Where od1.OrderID =1 _
Select od1)
For Each OrderDetail As ORM.Entities.OrderDetail In objOrderDetails
If Not OrderDetail.Requests Is Nothing Then
IF OrderDetail.Requests.Last.RequestType="Refund" Then
iRefund -= OrderDetail.UnitCost
End If
End If
Next
I have 2 Tables , OrderDetails and Requests In my LINQ to SQL dbml file.
OrderDetailsID is a foreign key in Requests Table.
I want to write the query to get the sum of UnitCost from OrderDetails based on OrderId.
And If there is a row in Requests Table for each OrderDetailsID, and the Requests.Last.RequestType="Refund" I want to reduce the total refund amount from the main sum otherwise If there is no row based on OrderDetailsID, add to sum.
Here is the way I implement that.
I am looking to prevent using "For each".
Any Solutions?
iRefund = (From od1 In dc.OrderDetails _
Where od1.OrderID =1 _
Select od1.UnitCost).Sum
Dim objOrderDetails = (From od1 In dc.OrderDetails _
Where od1.OrderID =1 _
Select od1)
For Each OrderDetail As ORM.Entities.OrderDetail In objOrderDetails
If Not OrderDetail.Requests Is Nothing Then
IF OrderDetail.Requests.Last.RequestType="Refund" Then
iRefund -= OrderDetail.UnitCost
End If
End If
Next
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想使用 Linq 而不是 for-each 循环,您可以使用 List 的 ForEach 扩展方法:
这假设 iRefund 是一个模块变量。
If you want to use Linq instead of a for-each loop, you could use the ForEach extension method of List:
This assumes that iRefund is a module variable.