在 VB.NET 中使用 LINQ 组连接
我试图弄清楚如何在 VB.NET 下的 LINQ 查询中使用组联接。出于某种原因,我似乎在语法上找到的每个示例都是完全错误的!至少,我的编译器一直这么告诉我。我在这里到底做错了什么?
这是一个简单的示例,我想将订单与其订单项目连接起来,以便最终得到一个包含按其 orderId 分组在一起的订单项目集合的类型:
Dim groupedOrders = (From o In orders
Group Join i In orderItems On o.OrderId Equals a.OrderId Into myOrders
Select o.OrderId, myOrders).ToList()
我当前在此示例中遇到的是 ' myOrders 组我正在创建错误:
在此上下文中无法访问方法“myOrders”的定义。
I'm trying to figure out how to use Group Joins in LINQ queries under VB.NET. For some reason, every example I seem to find on the syntax is just plain WRONG! At least, that's what my compiler keeps telling me. What is it exactly I'm doing wrong here?
This is a simple example where I want to join orders to their order items so that I end up with a type that contains a collection of order items grouped together by their orderId's:
Dim groupedOrders = (From o In orders
Group Join i In orderItems On o.OrderId Equals a.OrderId Into myOrders
Select o.OrderId, myOrders).ToList()
What I'm currently running into in this example is that the 'myOrders' group I'm creating errors out with:
Definition of method 'myOrders' is not accessible in this context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 VB 中,Into 别名需要是“Group”而不是 myOrders。使用 Northwind,您可以按如下方式声明您的查询:
如果您想将组别名为其他名称,您可以使用:
也就是说,如果您的订单和 orderItems 来自数据库提供程序,您可以只使用自然关联而不是根本需要连接:
此外,如果您只需要按外键分组,则不需要父表:
In VB, the Into alias needs to be "Group" not myOrders. Using northwind you could state your query as follows:
If you want to alias the group as something else, you can use:
That being said, if your orders and orderItems are coming from a database provider, you could just use the natural associations and not need the join at all:
Also, if you only need to group by the foreign key, you don't need the parent table:
你很接近了。您只需将
myOrders
指定为Group
:您可以从此 MSDN 页面查看类似的示例,包括如何获取组的
Count
: Visual Basic 中的 LINQ 简介。You're close. You just need to designate
myOrders
as aGroup
:You can see similar examples, including how to get the group's
Count
, from this MSDN page: Introduction to LINQ in Visual Basic.我喜欢包含 LINQ 查询的另一个示例,如果不是为了回答这个问题,那么只是为了保留我将来可以参考的副本:
其中 MyBase.QueryGlobalStatic() 是一个来自我的上下文的函数,按顺序允许我将这种代码放在任何地方,而不需要检查连接或身份验证数据(除其他外)。等价的将是这样的:
I like to include another example of a LINQ query, if not to answer this question then just in order to keep a copy that I can refer to in the future:
where MyBase.QueryGlobalStatic() is a function that comes from my context in order to allow me to put this kind of code anywhere without any need for checking for connections or authentication data (among other things). The equivalent will be something like: