我花了几个小时在这里和网上查看档案,了解如何迭代具有多个VB.Net分组的IGroup。 C#有很多解决方案,但我真的很难转换为VB.Net。
这是我正在分组的列表
dim merge_list As List(Of MergeData)
这是我的代码,按列表中的三个属性进行分组
Dim groups = merge_list.GroupBy(Function(t) New With {Key t.GUID.Category,
Key t.GUID.FeatureType,
Key t.GUID.AssetType}) _
.Where(Function(grp) grp.Count > 1)
接下来我尝试遍历群组,但由于我没有为群组列表中的项目提供类型(即昏暗群组As SomeType),因此我不知道如何使用它们。< / p>
这是循环群组的代码
dim group '===note there is no "As SomeType" for group just 'Dim group'===
For Each group In groups
' since group is not typed I cannot figure out how to work with it
next
有人可以告诉我如何使用VB.NET迭代多个组的IGoup吗?
答案 0 :(得分:2)
您不必在group
声明之外声明For Each
。检查以下代码:
Dim source = Enumerable.Range(0, 1000)
Dim groups = source.GroupBy(Function(x) New With {
Key .ByFive = x Mod 5,
Key .ByTen = x Mod 10,
Key .ByTwenty = x Mod 20})
For Each group In groups
Console.WriteLine("ByFive: {0}, ByTen: {1}, ByTwenty: {2}, Count: {3}",
group.Key.ByFive, group.Key.ByTen, group.Key.ByTen, group.Count())
Next
它编译得很好并打印:
ByFive: 0, ByTen: 0, ByTwenty: 0, Count: 50
ByFive: 1, ByTen: 1, ByTwenty: 1, Count: 50
ByFive: 2, ByTen: 2, ByTwenty: 2, Count: 50
ByFive: 3, ByTen: 3, ByTwenty: 3, Count: 50
ByFive: 4, ByTen: 4, ByTwenty: 4, Count: 50
ByFive: 0, ByTen: 5, ByTwenty: 5, Count: 50
ByFive: 1, ByTen: 6, ByTwenty: 6, Count: 50
ByFive: 2, ByTen: 7, ByTwenty: 7, Count: 50
ByFive: 3, ByTen: 8, ByTwenty: 8, Count: 50
ByFive: 4, ByTen: 9, ByTwenty: 9, Count: 50
ByFive: 0, ByTen: 0, ByTwenty: 10, Count: 50
ByFive: 1, ByTen: 1, ByTwenty: 11, Count: 50
ByFive: 2, ByTen: 2, ByTwenty: 12, Count: 50
ByFive: 3, ByTen: 3, ByTwenty: 13, Count: 50
ByFive: 4, ByTen: 4, ByTwenty: 14, Count: 50
ByFive: 0, ByTen: 5, ByTwenty: 15, Count: 50
ByFive: 1, ByTen: 6, ByTwenty: 16, Count: 50
ByFive: 2, ByTen: 7, ByTwenty: 17, Count: 50
ByFive: 3, ByTen: 8, ByTwenty: 18, Count: 50
ByFive: 4, ByTen: 9, ByTwenty: 19, Count: 50
在处理group
内的For Each
时,您甚至可以获得智能感知!
答案 1 :(得分:2)
只需使用嵌套的For Each: -
For Each item In groups
Console.WriteLine(item.Key.GUID.Category) //You can access only `Keys` here
For Each inneritem In item
Console.WriteLine(inneritem.GUID.Category)
//so on (You can access all the properties here)
Next
Next
选中Fiddle。