2011-10-14 3 views
7

で2次元配列上の各ループのために私は、2Dループの第1のアレイを通過するループを書いている、と私は現在、このようにそれを持っている:はVB.NET

For Each Dir_path In MasterIndex(, 0) 
    'do some stuff here 
Next 

しかし、それは私を与えています最初のフィールドに式が必要であるとエラーします。しかし、それは私がやろうとしていることです、最初のフィールドをループします。これをどうやって解決するのですか?私はそこに何を入れるだろうか?

編集:明確にする、私は特に、第2フィールドは常に0

+0

は、私はあなたのより詳細な要求 – JoshHetland

答えて

14

あなたがループの場合、ネストされたと

注これを達成することができる:配列の要素を反復処理するために、各ループについて使用する場合、各反復で生成されたプレースホルダは、実際の配列内の値のコピーです。その値の変更は元の配列に反映されません。情報を読む以外のことをしたい場合は、配列要素を直接扱うためにForループを使う必要があります。

2次元配列を仮定すると、次のコード例は各次元の各要素に値を割り当てます。

Dim MasterIndex(5, 2) As String 

For iOuter As Integer = MasterIndex.GetLowerBound(0) To MasterIndex.GetUpperBound(0) 
    'iOuter represents the first dimension 
    For iInner As Integer = MasterIndex.GetLowerBound(1) To MasterIndex.GetUpperBound(1) 
    'iInner represents the second dimension 
    MasterIndex(iOuter, iInner) = "This Isn't Nothing" 'Set the value 
    Next 'iInner 

    'If you are only interested in the first element you don't need the inner loop 
    MasterIndex(iOuter, 0) = "This is the first element in the second dimension" 
Next 'iOuter 
'MasterIndex is now filled completely 

オプションで、コンラートルドルフのようなギザギザの配列が示唆された上で、あなたがループする場合(これは機能的に、より密接に、より緩く他に、アレイの実装と一致する動的

各次元上を反復する .Rankプロパティを使用することができますPHPのような型付き言語で)あなたはそうのようにそれについて行くことができます:

'This is a jagged array (array of arrays) populated with three arrays each with three elements 
Dim JaggedIndex()() As String = { 
    New String() {"1", "2", "3"}, 
    New String() {"1", "2", "3"}, 
    New String() {"1", "2", "3"} 
} 

For Each aOuter As String() In JaggedIndex 
    'If you are only interested in the first element you don't need the inner for each loop 
    Dim sDesiredValue As String = aOuter(0) 'This is the first element in the inner array (second dimension) 

    For Each sElement As String In aOuter 
    Dim sCatch As String = sElement 'Assign the value of each element in the inner array to sCatch 
    sElement = "This Won't Stick" 'This will only hold value within the context of this loop iteration 
    Next 'sElement 
Next 'aOuter 
'JaggedIndex is still the same as when it was declared 
1

あなたは単純にできないです理由です、各配列の部分配列で0番目の要素を探しています。多次元配列は、.NETフレームワークインフラストラクチャでは実際にはサポートされていません。彼らは後の考えとしてタグ付けされているようだ。最も良い解決策は、しばしばそれらを使用することではなく、ギザギザの配列(Integer(,)ではなく配列Integer()()の配列)を使用することです。

+0

を考慮するために、両方の例を更新し 'が、私は再ときだから私は)MasterIndex()('にそれを変更しましたMasterIndex(、0) 'に' For Each Dir_path For MasterIndex()(0) 'を置くと'インデックスの数はインデックス付き配列の次元数よりも少ない 'となるでしょうか? – jayjyli

+1

@Timその構文は単に無効です。 'For Each x in MasterIndex ... DirPath = x(0)'を使用し、そこから作業してください... –