我有一个二维数组
string[,] table = new string[,] {{"001","caojw","90"},
{"002","caij","89"},
{"003","shaohx","92"}};我想通过foreach取得每一行的第三个数据,于是我这样做
foreach(string[] list in table)
{
Console.Write("{0} ",list[2]);
}
结果编译不过,提示string不能转换为string[],
大大们,请问我该怎么改正才能实现我要的效果,当然是在使用foreach的前提下,新手上路大家多帮帮忙吧
string[,] table = new string[,] {{"001","caojw","90"},
{"002","caij","89"},
{"003","shaohx","92"}};我想通过foreach取得每一行的第三个数据,于是我这样做
foreach(string[] list in table)
{
Console.Write("{0} ",list[2]);
}
结果编译不过,提示string不能转换为string[],
大大们,请问我该怎么改正才能实现我要的效果,当然是在使用foreach的前提下,新手上路大家多帮帮忙吧
{
Console.Write(list);
}这个是可以执行的.
string[][]是数组的数组,枚举时以string[]为单位
string[,]是二维数组,枚举时以string为单位
{
if (!IsPostBack)
{
string[,] table = new string[,] {{"001","caojw","90"},
{"002","caij","89"},
{"003","shaohx","92"}};
for (int i = 0; i < table.GetLength(1); i++)
{
foreach (string score in ArrayItems(table, i,2))
{
Response.Write(score + "</br>");
}
}
}
} /// <summary>
/// 实现一个迭代器
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="colindex"></param>
/// <param name="rowindex"></param>
/// <returns></returns>
IEnumerable<T> ArrayItems<T>(T[,] data, int colindex,int rowindex)
{
yield return data[colindex, rowindex];
}
string[][] table = new string[][] {new string[]{"001","caojw","90"},new string[]
{"002","caij","89"},
new string[]
{"003","shaohx","92"}};
foreach (string[] list in table)
{
Console.WriteLine("{0} ", list[2]);
}
Console.ReadLine();
1.type[][],二维数组,数组的是维度固定的,例如:
int[,] array = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
2.type[,],锯齿数组(交错数组),例如:
int[][] Array2 = new int[][]
{
new int[] {1,2},
new int[] {3,4},
new int[] {5,6}
}
{
Console.Write("{0} ",list);
}这样就没问题拉,table是数据,遍历时就不是数据啦
{"001","cjw","90"},
{"002","cj","89"},
{"003","shx","92"},
{"004","ly","77"}
};
Console.WriteLine(table.GetLength(0));//输出4
Console.WriteLine(table.GetLength(1));//输出3
Console.ReadKey(true);这是我的一点疑问,GetLength函数又让我糊涂了,看你的代码中用的GetLength(1),是不是有点问题
table.GetLength(0) 获得第一维的长度(行数),table.GetLength(1)获得第二维的长度(列数)。