我建议使用LINQ:
int[] promotionIDs = (from dr in ds.Tables[0].AsQueryable()
where dr.Field<string>("Status") == "Active"
select dr.Field<int>("Id")).ToArray();
如果你想解决您的代码,而不是,让我告诉你什么地方错了:
foreach (DataRow dr in ds.Tables[0].Rows[i]["Status"].ToString() == "Active")
在什么地方i
来从?你正在使用foreach
,所以你不需要计数器变量。你的循环应该看起来像这样:
foreach (DataRow dr in ds.Tables[0].Rows) {
if (dr.Field<string>("Status") == "Active") {
...
}
}
现在,如何将Id添加到数组中。你在这里做什么?
promotionID = new int[] { Convert.ToInt32(dr["Id"]) };
...是创造一个价值,这是当前记录的ID的新阵列(那是在它扔掉一切)。数组不是用于添加项目的好数据结构。让我建议使用,而不是一个列表:
List<int> promotionIDs = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows) {
if (dr.Field<string>("Status") == "Active") {
promotionIDs.Add(dr.Field<int>("Id"));
}
}
如果您仍需要一个数组,日后可以转换:
int[] promotionIDArray = promotionIDs.ToArray();
你值得所有的好友!谢谢:) – Ram 2010-11-18 16:26:12
不客气。 – 2010-11-18 16:43:58