18

给定....

Public MasterList as IEnumerable(Of MasterItem)
Public Class MasterItem(Of T) 
    Public SubItems as IEnumerable(Of T)
End Class 

我想要一个 IEnumerable(Of T) 它将遍历 MasterList 中所有 MasterItems 的所有 SubItems

我想认为有一个 Linq 工具可以做到这一点,或者我忽略了一个扩展方法。我需要一种在 VB9 (2008) 中工作的机制,因此不使用 Yield。

4

5 回答 5

27

您在寻找 SelectMany() 吗?

MasterList.SelectMany(master => master.SubItems)

对不起C#,不懂VB。

于 2009-06-30T11:50:58.613 回答
8

您可以通过 Linq 使用 SelectMany 实现此目的

C# 代码

masterLists.SelectMany(l => l.SubItems);


此致

于 2009-06-30T11:51:16.367 回答
8

Enumerable.SelectManyIEnumerablemonad 的关键,就像它的 Haskell 等效项一样concatMap, 是 Haskell 列表单子的关键。

事实证明,您的问题直指计算机科学深层的核心。

你会想要小心你的措辞,因为这Aggregate意味着一些非常不同的东西SelectMany- 甚至相反。Aggregate将一个IEnumerable值组合成一个值(可能是另一种类型),而SelectMany un将一个IEnumerable值组合成更多值(可能是另一种类型)。

于 2009-07-01T13:05:08.677 回答
3

只是为了提供真正的 VB.NET 答案:

' Identical to Per Erik Stendahl's and Oliver Hanappi's C# answers
Dim children1 = MasterList.SelectMany(Function(master) master.SubItems)

' Using VB.NET query syntax
Dim children2 = From master In MasterList, child in master.SubItems Select child

' Using Aggregate, as the question title referred to
Dim children3 = Aggregate master In MasterList Into SelectMany(master.SubItems)

这些都编译为相同的 IL,除了children2需要Function(master, child) child.

于 2014-02-05T01:44:16.277 回答
1

我知道在 C# 中有yield循环运算符。只需yield return递归地迭代每个子项。显然,VB 没有yield,抱歉。

于 2009-06-30T11:50:01.767 回答