大大们,C#中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的前提下,新手上路大家多帮帮忙吧
[解决办法]
可以实现,代码如下:
protected void Page_Load(object sender, EventArgs e)
{
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];
}