如何在多维数组中获取数组的值...在另一个数组中?
我希望在以下代码中按升序获取test
的值。
我尝试使用for
和foreach
循环,但在引用多维数组的元素时遇到了问题。
static void Main(string[] args)
{
string[][,][] test = { new string[,][]{{
new string[]{"test1","test2","test3"},
new string[]{"test4","test6","test6"}
},
{
new string[]{"test7","test7","test9"},
new string[]{"test10","test11","test12"}
}},
new string[,][]{{
new string[]{"test13","test14","test15"},
new string[]{"test16","test17","test18"}
},
{
new string[]{"test19","test20","test21"},
new string[]{"test22","test23","test24"}
}}
};
for (int a = 0; a < test.Count(); a++ )
{
foreach(var am in test[a])
{
for (int ama = 0; ama < am.Count(); ama++)
{
Console.WriteLine("{0}",test[a][0,0][ama].ToString()); //what should I put in [0,0]?
}
}
}
Console.ReadKey();
}
答案 0 :(得分:2)
为什么不:
Console.WriteLine("{0}", am[ama].ToString());
答案 1 :(得分:2)
您可以使用foreach
,而不是使用for
,如下所示:
for ( int a = 0; a < test.Count(); a++ )
{
string[,][] ta = test[a];
for( int i1 = 0; i1 < ta.GetLength( 0 ); i1++ )
{
for( int i2 = 0; i2 < ta.GetLength( 1 ); i2++ )
{
string[] am = ta[i1, i2];
for ( int ama = 0; ama < am.Count(); ama++ )
{
Console.WriteLine( "{0}", test[ a ][ i1, i2 ][ ama ].ToString() );
}
}
}
答案 2 :(得分:2)
莱昂内尔,
以下是您的代码:
static void Main(string[] args)
{
string[][,][] test = { new string[,][]{{
new string[]{"test1","test2","test3"},
new string[]{"test4","test5","test6"}
},
{
new string[]{"test7","test8","test9"},
new string[]{"test10","test11","test12"}
}},
new string[,][]{{
new string[]{"test13","test14","test15"},
new string[]{"test16","test17","test18"}
},
{
new string[]{"test19","test20","test21"},
new string[]{"test22","test23","test24"}
}}
};
for (int a = 0; a < test.Count(); a++)
{
foreach(string[] am in test[a])
{
for (int ama = 0; ama < am.Count(); ama++)
{
Console.WriteLine("{0}", am[ama].ToString()); //Reference to the inside loop
}
}
}
Console.ReadKey();
}
无需在print语句中引用整个数组。您只需要引用内部循环。希望有所帮助。
祝福, 比尔