Ross Presser
Ross Presser

Reputation: 6255

What's the syntax for returning a collection of collections?

The code below shows how I am attempting to return a collection of collections of objects. Using the lambda-based LINQ syntax, I get what I want. Using the "natural language" syntax, I don't; I get a flat collection of objects. What's the phraseology to get a collection of collections?

Option Strict On

Sub Main

    Dim i As Integer
    Dim j As Integer
    Dim l As List(Of List(Of MyPoint)) = New List(Of List(Of MyPoint))
    For j = 1 To 2
        Dim ll = New List(Of MyPoint)
        For i = 1 To 10
            ll.Add(New MyPoint(i,j))
        Next
        l.Add(ll)
    Next

    Dim q1 = l.Select(Function (ll) ll.Select(Function (p) New MyPoint(p.x+1, p.y+1)))

    Dim q2 = From ll In l From p In ll Select New MyPoint(p.x + 1, p.y + 1)



End Sub

Public Class MyPoint
    Public Property X As Integer
    Public Property Y As Integer
    Sub New(i As Integer, j As Integer)
        X = i
        Y = j
    End Sub
End Class

EDIT: Using real class instead of anonymous type, and Option Strict On, so you can focus on the actual question instead of arguing with me.

Upvotes: 0

Views: 330

Answers (1)

James Curran
James Curran

Reputation: 103525

You have two Selects in the first one. You need two Selects in the second one also; (I renamed some things so it's easier to read)

Dim i As Integer, j As Integer
Dim listOfLists As List(Of List(Of Point)) = New List(Of List(Of Point))
For j = 1 To 2
    Dim ll = New List(Of Point)
    For i = 1 To 10
        ll.Add(New Point With {.x = i, .y = j})
    Next
    listOfLists.Add(ll)
Next

' This returns what I want    
Dim q1 = listOfLists.Select(Function(ll) ll.Select(Function(p) New With {.x = p.x + 1, .y = p.y + 1}))

Dim q2 = From thisList In listOfLists 
          Select From pnt In thisList 
                 Select New Point With {.x = pnt.x + 1, .y = pnt.y + 1}

Upvotes: 2

Related Questions