我建议使用 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"]) };
...是用一个值创建一个 new 数组(丢弃其中的所有内容),该值是当前记录的 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();