我有一个包含6个值列表的数据表。我想迭代这个表并将每个新行值分配给另一个变量。该表由名为DataTasks的类填充。
这就是我现在这样做的方式,但我相信一定有更好,更简洁的方法吗?
DataTable dt = new DataTable();
dt = DataTasks.CreateDataTableFromSQL(strSQL);
// Loop counter
int i = 0;
foreach (DataRow row in dt.Rows)
{
// Assign ranges - this is where I hope to have better code!!
switch(i)
{
case 0:
SomeClass.Range1 = (int)row["Range"];
break;
case 1:
SomeClass.Range2 = (int)row["Range"];
break;
case 2:
SomeClass.Range3 = (int)row["Range"];
break;
case 3:
SomeClass.Range4 = (int)row["Range"];
break;
case 4:
SomeClass.Range5 = (int)row["Range"];
break;
case 5:
SomeClass.Range6 = (int)row["Range"];
break;
default:
break;
}
// Increment counter
i++;
}
答案 0 :(得分:2)
嗯,从它的外观来看,你只需要分配' Range'的值。取决于它是什么行号。那么为什么不在for循环中执行此操作并使用索引执行此操作。这假设数据表中的行数当然是6。
这样的事情应该有效:
SomeClass.Range1 = (int)dt.Rows[0]["Range"]; //Gets value in 'Range' column in first row.
SomeClass.Range2 = (int)dt.Rows[1]["Range"]; //Gets value in 'Range' column in second row.
//Add more here.
答案 1 :(得分:0)
您可以尝试将所有范围存储在数组中
DataTable dt = new DataTable();
dt = DataTasks.CreateDataTableFromSQL(strSQL);
// Loop counter
int i = 0;
int[] ranges = new int[6];
//assuming you have 6 rows
foreach (DataRow row in dt.Rows)
{
ranges[i] = (int)row["Range"];
i++;
}