Freigeben über


Flattening a nested list using queries.

This seems to be a common question - " I have a list of lists (or array or arrays), how can I flatten it into a single list/array? "

It is surprisingly trivial to do with queries. It takes one line of code -

Module Module1

    Sub Main()

        'create a list of lists

        Dim list As New List(Of List(Of Integer))

        For i = 0 To 5

      Dim inner_list As New List(Of Integer)

            For j = 0 To 3

                inner_list.Add(j)

            Next

            list.Add(inner_list)

        Next

        '======

        ' get flattened IEnumerable

        '=====

        Dim q = From i In list, j In i Select j

        'print out the sequence

        For Each j In q

            Console.Write(j)

        Next

        Console.WriteLine()

        'can make it into an array if needed

        Dim arr() As Integer = q.ToArray

        'print out the array

        For Each j In arr

            Console.Write(j)

        Next

        Console.WriteLine()

    End Sub

End Module