0

我花了几个小时浏览这里和网络上的档案,以了解如何迭代具有多个 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),所以我不知道如何使用它们。

这是我循环遍历组的代码

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 吗?

4

2 回答 2

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

于 2014-12-30T01:48:21.937 回答
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

检查这个小提琴

于 2014-12-30T01:48:59.563 回答