List<T>は任意の型Tに型付けしたリストを作成できるため、TにList<T>を指定すれば入れ子になったリストList<List<T>>を作成することが出来ます。 例えば可変長のジャグ配列のようなものを作成したい場合は、Listを入れ子にすることで実現できます。 入れ子になったListを列挙する場合、例えばList<List<int>>を列挙すると、List<List<int>>に含まれているList<int>を一つずつ取り出せます。
次の例では、入れ子になったListを作成し、追加や削除・列挙などの操作を行っています。
Listを入れ子にして扱う
Imports System
Imports System.Collections.Generic
Class Sample
Shared Sub Main()
' 入れ子になったListを作成
Dim dictionary As New List(Of List(Of String))()
' Listの中にListを追加
dictionary.Add(New List(Of String)(New String() {"apple", "action", "after"})) ' 'a'で始まる単語のList
dictionary.Add(New List(Of String)(New String() {"big", "best", "bridge"})) ' 'b'で始まる単語のList
dictionary.Add(New List(Of String)(New String() {"cheese", "cat", "connect"})) ' 'c'で始まる単語のList
dictionary(0).Add("add") ' 'a'で始まる単語のListにアイテムを追加
dictionary(1).Add("book") ' 'b'で始まる単語のListにアイテムを追加
dictionary(2).Remove("connect") ' 'c'で始まる単語のListからアイテムを削除
' 'd'で始まる単語のListを作成
Dim wordsStartWithD As New List(Of String)(New String() {"drink", "dear", "dig"})
' 作成したListを入れ子になっているListの2番目に追加
dictionary.Insert(1, wordsStartWithD)
' すべての単語のListをソートする
For Each words As List(Of String) In dictionary
words.Sort()
Next
' 入れ子になっているListの内容を表示
For Each words As List(Of String) In dictionary
' Listの中にあるListの内容を表示
For Each word As String In words
Console.Write("{0} ", word)
Next
Console.WriteLine()
Next
End Sub
End Class
実行結果
action add after apple dear dig drink best big book bridge cat cheese
上記の例では2段階に入れ子になったListを作成しましたが、必要ならばList<List<List<int>>>といった3段階以上に入れ子になったListを作成することも可能です。
このように、Listを入れ子にすることで可変長のジャグ配列と同様の構造を作成することができますが、一方Listでは可変長の多次元配列(矩形配列)の構造を単純に作成することはできません。 またそういったコレクションクラスも用意されていないため、独自に実装する必要があります。
関連: 多次元配列・ジャグ配列