下面是我的代码
string Cmp_Cd_Typ_Id1_1 = "";
for (a = 0; a < dsDeviceMatch2.Tables[0].Columns.Count; a++)
{
for (b = 0; b < dsDeviceMatch2.Tables[0].Columns.Count; b++)
{
Cmp_Cd_Typ_Id1_1 = Cmp_Cd_Typ_Id1_1 + dsDeviceMatch2.Tables[0].Rows[a][b].ToString() + ",";
}
}
正在将数据保存在 Cmp_Cd_Typ_Id1_1 变量中。我需要分别保存每次迭代的数据,但在这里我得到的结果是 a、b、c、d。但我需要单独保存一个 b 等。我怎样才能做到这一点
最佳答案
索引器 a
应该应用于 Rows 集合,而不是 Columns 集合
for (a = 0; a < dsDeviceMatch2.Tables[0].Rows.Count; a++)
还强烈建议使用 StringBuilder而不是像那样的字符串连接
StringBuilder result = new StringBuilder();
for (int a = 0; a < dsDeviceMatch2.Tables[0].Rows.Count; a++)
{
for (int b = 0; b < dsDeviceMatch2.Tables[0].Columns.Count; b++)
{
result.Append(dsDeviceMatch2.Tables[0].Rows[a][b].ToString() + ",");
}
}
string Cmp_Cd_Typ_Id1_1 = result.ToString();
相反,如果您希望行彼此分开,那么您需要在这种方法中添加一个 List<strings>
// Each row will be an element of this list
List<string> rows = new List<string>();
for (int a = 0; a < dsDeviceMatch2.Tables[0].Rows.Count; a++)
{
StringBuilder result = new StringBuilder();
for (int b = 0; b < dsDeviceMatch2.Tables[0].Columns.Count; b++)
{
result.Append(dsDeviceMatch2.Tables[0].Rows[a][b].ToString() + ",");
}
// Add the row to the list removing the last comma
rows.Add(result.ToString(0, result_1.Length - 1);
}
关于c# - 在c#中将数据保存在嵌套的for循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618228/