c# - 使用 LINQ,我可以像在 C# 中那样在 VB.NET 中为 "grouping"命名吗?

标签 c# vb.net linq

我的目标是对数据进行分组和转换,但同时提供已转换和未转换的“分组数据”。

考虑以下最小的 C# 示例:

var data = new[] { ("a", 1), ("a", 2), ("b", 1) };

var groupedAndTransformed =
    from d in data
    group d by d.Item1 into g
    select new
    {
        Untransformed = g,
        Transformed = g.Key + string.Join(",", g.Select(tuple => tuple.Item2))
    };

现在我尝试在 VB.NET 中执行相同的操作,但只能通过两步过程来实现,因为 VB.NET 的 Group By 的工作方式与 C# 的 group 有所不同通过:

Dim data = {("a", 1), ("a", 2), ("b", 1)}

Dim step1 =
    From d In data
    Group d By d.Item1 Into Group

Dim groupedAndTransformed =
    From g In step1
    Select
        Untransformed = g,
        Transformed = g.Item1 + String.Join(",", g.Group.Select(Function(tuple) tuple.Item2))

问题似乎是 VB.NET 的 Group By 将分组结果放入某种“全局命名空间”中:如果我在 Group d By 之后直接继续编写 LINQ 代码d.Item1 Into Group,我在范围内同时拥有 Item1Group 。但是,我没有由它们组成的 IGrouping 的名称(在 C# 中称为 g),因此我需要第二步。

我可以以某种方式告诉 VB 的 Group By 语句为我提供 IGrouping 的名称吗? 我发现的唯一其他解决方法是使用(a) 函数式语法而不是声明性 LINQ 语法(即直接调用 Enumerable.GroupBy)或 (b) 将 step1 嵌套到第二步中(即 From g In (...step1 ...))。有什么我错过的吗?

最佳答案

遗憾的是,C# 和 VB LINQ 语法如此不兼容。 我认为以下 VB LINQ 与原始版本最接近(当然使用 Option Infer On):

Dim data = { ("a", 1), ("a", 2), ("b", 1) }

Dim groupedAndTransformed = From d In data
    Group d By d.Item1 Into g = Group
    Select New With {
        Key .Untransformed = g,
        Key .Transformed = Item1 & String.Join(",", g.Select(Function(tuple) tuple.Item2))
    }

我已经测试过,它可以编译并运行,但很难判断它的功能是否相同。

关于c# - 使用 LINQ,我可以像在 C# 中那样在 VB.NET 中为 "grouping"命名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71828926/

相关文章:

c# - 将值类型转换为泛型

c# - Azure物联网中心: Can't call direct method using AMQP protocol

c# - DataGridView 不在 ToolStripDropDown 中显示数据

c# - 如何在两种方法之间共享一个 LINQ 查询?

c# - 为什么此 Linq 不起作用(将 Linq 表达式翻译为 URI : Can only specify query options (orderby, 时出错,其中,采取,跳过)

c# - CQRS + ES - 在哪里查询业务逻辑所需的数据?

c# - MVVM WPF 应用程序开发人员技能集

sql - 是什么原因导致 “Syntax error in INSERT INTO statement”

javascript - 刷新 Autopostback 下拉列表上的 Javascript 代码

.net - 使用 LINQ to SQL 获取 "string"列的最大长度