【问题标题】:VB.NET GroupBy element selector parameter type cannot be inferredVB.NET GroupBy 元素选择器参数类型无法推断
【发布时间】:2018-03-06 20:33:10
【问题描述】:

我可以在 c# 中毫无问题地做到这一点:

public class Whatever
{
    public string State { get; set; }
    public string City { get; set; }
}

var whatevers = new[] {
    new Whatever { State = "SomeState", City = "Eastville" },
    new Whatever { State = "SomeState", City = "Southville" }
};

var group = whatevers.GroupBy(
    x => x.State, x => x.City, 
    (k, v) => new { State = k, Cities = v.ToArray() }
).ToArray();

但 VB.NET 似乎存在推理问题:

Option Infer On

Public Class Whatever
    Property State As String
    Property City As String
End Class

Dim whatevers = New Whatever() {
    New Whatever With {.State = "SomeState", .City = "Eastville"},
    New Whatever With {.State = "SomeState", .City = "Southville"}
}

Dim group = whatevers.GroupBy(
    Function(x) x.State,
    Function(x) x, 'this is the problem; see below
    Function(k, v) New With {.State = k, .Cities = v.ToArray()}
).ToArray()

对于我的元素选择器,我想返回 Function(x) x.City。如果我没有指定.Cityx 会正确推断为Whatever。但是,在我输入.City 的那一刻,x 无法再被推断出来。

我在这上面花了一个多小时,所以有时间来 SE。

【问题讨论】:

    标签: vb.net linq group-by


    【解决方案1】:

    一点点修复就能发挥作用。

    Public Class Whatever
      Property State As String
      Property City As String
    End Class
    
    Dim whatevers = New Whatever() {
        New Whatever With {.State = "SomeState", .City = "Eastville"},
        New Whatever With {.State = "SomeState", .City = "Southville"}
    }
    
    Dim group = whatevers.GroupBy(
        Function(x As Whatever) x.State,
        Function(x As Whatever) x.City, 'this is not the problem;
        Function(k, v) New With {.State = k, .Cities = v.ToArray()}
    ).ToArray()
    

    【讨论】:

    • 成功了!不知道为什么你必须在 VB.NET 中这样做,而不是 C#。
    • 在 VB.NET 中也有很多事情是可能的,但在 C# 中是不可能的:)
    • 我实际上认为这是 IDE 中的错误而不是功能。一开始它可以推断出类型,但是一旦我使用了类型初始化器,它就无法推断出。
    • 这很有可能。尝试在 VS 中使用“报告问题...”命令,但不要期望除“分类”之外的任何响应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    相关资源
    最近更新 更多