You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将C# Linq转换为VB.Net Linq时遇Key成员不存在错误求助

VB.Net Linq分组报错:Key is not a member of 'IEnumerable(Of DataRow)'

场景与需求

我从SQL Server通过存储过程获取了一个DataTable,数据构造示例如下(C#代码):

DataTable dt = new DataTable("Products");
dt.Columns.Add("ProductID");
dt.Columns.Add("CustomerID");
dt.Columns.Add("CustomerState");
dt.Columns.Add("CustomerCity");

object[] o = { 1, 1, "TX", "Austin" };
dt.Rows.Add(o);

object[] o1 = { 2, 2, "AZ", "Phoenix" };
dt.Rows.Add(o1);

object[] o2 = { 2, 3, "OK", "Oklahoma" };
dt.Rows.Add(o2);

object[] o3 = { 2, 4, "CO", "Denver" };
dt.Rows.Add(o3);

object[] o4 = { 3, 1, "TX", "Austin" };
dt.Rows.Add(o4);

需要实现按ProductID分组,将相同ProductID对应的其他字段用分号拼接,最终目标结果如下:

ProductIDCustomerIDCustomerStateCustomerCity
11TXAustin
22;3;4AZ;OK;COPhoenix;Oklahoma;Denver
31TXAustin

可行的C# Linq代码

对应的C# Linq代码可以正常运行:

var results = from p in dt.AsEnumerable()
    group p by p.Field<string>("Productid") into g
    select new
    {
        ProductId = g.Key,
        CustomerId = string.Join(";", from i in g select i.Field<string>("CustomerID")),
        CustomerState = string.Join(";", from i in g select i.Field<string>("CustomerState")),
        CustomerCity = string.Join(";", from i in g select i.Field<string>("CustomerCity")),
    };

我的VB.Net代码与报错

尝试转换为VB.Net代码时出现错误,代码如下:

Dim results = From p In dt.AsEnumerable() 
    Group p By ProductID = p.Field(Of String)("ProductID") Into g = Group
    Select New With {
        Key .ProductID = g.Key,
        .CustomerId = String.Join(";", From i In g Select i.Field(Of String)("CustomerId")),
        .CustomerState= String.Join(";", From i In g Select i.Field(Of String)("CustomerState")),
        .CustomerCity= String.Join(";", From i In g Select i.Field(Of String)("CustomerCity"))
    }

报错信息:

Key is not a member of 'IEnumerable(Of DataRow)'

错误出现在g.Key这一行,作为VB.Net新手,需要解决这个问题。

解决方法

VB.Net的Linq分组语法和C#存在差异:当使用Group p By [分组字段变量] = ... Into g = Group时,分组的键值就是你在By后面定义的变量名,不需要通过g.Key访问。

修改后的正确VB.Net代码如下:

Dim results = From p In dt.AsEnumerable() 
    Group p By ProductID = p.Field(Of String)("ProductID") Into g = Group
    Select New With {
        Key .ProductID = ProductID, ' 直接使用分组时定义的ProductID变量
        .CustomerId = String.Join(";", From i In g Select i.Field(Of String)("CustomerID")),
        .CustomerState = String.Join(";", From i In g Select i.Field(Of String)("CustomerState")),
        .CustomerCity = String.Join(";", From i In g Select i.Field(Of String)("CustomerCity"))
    }

额外注意

原代码中CustomerId的大小写与DataTable中的CustomerID不一致,建议统一字段名的大小写,避免运行时出现找不到字段的异常。

内容的提问来源于stack exchange,提问作者Massey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:37:02