我可以在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了。
答案 0 :(得分:2)
小修复可以发挥魔力。
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()