【发布时间】: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。如果我没有指定.City,x 会正确推断为Whatever。但是,在我输入.City 的那一刻,x 无法再被推断出来。
我在这上面花了一个多小时,所以有时间来 SE。
【问题讨论】: