以下のコードを参照してください。1次元のインデックスを持つ多次元配列にアクセスする方法は何ですか。Foreachはそれを行うことができます。ええ、私は知っています、yieldのIEnumerableはインデックスと同じではありません。foreachを使用して新しい配列を作成する必要がありますか?または、新しいアレイを作成せずにそれを行うことはできますか?
int[,] myArray = new int[2, 2];
myArray[0,0] = 1;
myArray[1,1] = 2;
myArray[0,0] = 3;
myArray[1,1] = 4;
foreach (var value in myArray)
{
Console.Write(value);
}
var valueAtIndex = myArray[2]; //Won't compile, error: Wrong number of indices inside []; expected 2
値を読み取るだけでなくforeach
、配列をトラバースするのと同じ順序で値を設定する場合は、次の一般的なインデクサークラスを使用できます。
public class ArrayIndexer
{
readonly int totalLength;
readonly int lastIndexLength;
readonly int[] lengths;
readonly int[] lowerBounds;
int current;
readonly int[] currentZeroBased;
public ArrayIndexer(int[] lengths, int[] lowerBounds)
{
lastIndexLength = lengths[lengths.Length - 1];
totalLength = lengths[0];
for (int i = 1; i < lengths.Length; i++)
{
totalLength *= lengths[i];
}
this.lengths = lengths;
this.lowerBounds = lowerBounds;
currentZeroBased = new int[lengths.Length];
current = -1;
}
public bool MoveNext()
{
current++;
if (current != 0)
{
int currLastIndex = current % lastIndexLength;
currentZeroBased[currentZeroBased.Length - 1] = currLastIndex;
if (currLastIndex == 0)
{
for (int i = currentZeroBased.Length - 2; i >= 0; i--)
{
currentZeroBased[i]++;
if (currentZeroBased[i] != lengths[i])
break;
currentZeroBased[i] = 0;
}
}
}
return current < totalLength;
}
public int[] Current
{
get
{
int[] result = new int[currentZeroBased.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = currentZeroBased[i] + lowerBounds[i];
}
return result;
}
}
}
そして、配列全体を設定するために次のように使用できます。
int[,] myArray = new int[2, 2];
ArrayIndexer arrayIndexer = new ArrayIndexer(new[] {2, 2}, new[] {0, 0});
int i = 0;
while (arrayIndexer.MoveNext())
{
myArray.SetValue(++i, arrayIndexer.Current);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加