How do I Aggregate multiple IEnumerables of T

后端 未结 5 1770
春和景丽
春和景丽 2021-02-12 18:20

Given....

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

I

相关标签:
5条回答
  • 2021-02-12 18:48

    Enumerable.SelectMany is the key to the IEnumerable monad, just as its Haskell equivalent, concatMap, is the key to Haskell's list monad.

    As it turns out, your question goes right to the heart of a deep aspect of computer science.

    You will want to be careful with your phrasing, because Aggregate means something very different from SelectMany - even the opposite. Aggregate combines an IEnumerable of values into a single value (of possibly another type), while SelectMany uncombines an IEnumerable of values into even more values (of possibly another type).

    0 讨论(0)
  • 2021-02-12 18:52

    I know in C# there is the yield operator for loops. Just iterate and yield return each sub item recursively. Apparently, there is no yield for VB, sorry.

    0 讨论(0)
  • 2021-02-12 19:02

    Just to provide true VB.NET answers:

    ' 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)
    

    These all compile down to the same IL, except children2 requires the equivalent of Function(master, child) child.

    0 讨论(0)
  • 2021-02-12 19:06

    You can achieve this by Linq with SelectMany

    C# Code

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


    Best Regards

    0 讨论(0)
  • 2021-02-12 19:08

    Are you looking for SelectMany()?

    MasterList.SelectMany(master => master.SubItems)
    

    Sorry for C#, don't know VB.

    0 讨论(0)
提交回复
热议问题