C# 从数据集添加到int数组

C# 从数据集添加到int数组,c#,ado.net,C#,Ado.net,我必须将状态值与“Active”相同的数据集中的所有Id添加到int数组PromotionID中。这怎么可能呢。我错过了什么 int[] promotionID; foreach (DataRow dr in ds.Tables[0].Rows[i]["Status"].ToString() == "Active") { promotionID = new int[] { Convert.ToInt32(dr["Id"]) }; } 错误是: foreach语句无法对“bool”类型

我必须将状态值与“Active”相同的数据集中的所有Id添加到int数组PromotionID中。这怎么可能呢。我错过了什么

int[] promotionID;
foreach (DataRow dr in ds.Tables[0].Rows[i]["Status"].ToString() == "Active")
{

    promotionID = new int[] { Convert.ToInt32(dr["Id"]) };
}
错误是:

foreach语句无法对“bool”类型的变量进行操作,因为“bool”不包含“GetEnumerator”的公共定义


不能在foreach循环中使用筛选条件。试试这个:

int[] promotion;
foreach (DataRow dr in ds.Tables[0].Rows)
{
    if (dr["Status"].ToString() == "Active")
       promotionID = new int[] { Convert.ToInt32(dr["Id"]) };
}
这就解决了问题中的错误部分,但是您使用的
promotionID
看起来不正确,因为您在每次正匹配时都会覆盖它。您应该使用
列表
而不是
int[]
并使用
promotion.Add(Convert.ToInt32(dr[“Id]”))
将数字添加到列表中。这看起来像:

var promotion = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
    if (dr["Status"].ToString() == "Active")
       promotion.Add(Convert.ToInt32(dr["Id"]));
}
var升级=新列表();
foreach(ds.Tables[0].行中的数据行dr)
{
如果(dr[“状态”].ToString()=“活动”)
升级添加(转换为32(dr[“Id”]);
}
另一个选项是LINQ as。

我建议使用LINQ:

int[] promotionIDs = (from dr in ds.Tables[0].AsQueryable()
                      where dr.Field<string>("Status") == "Active"
                      select dr.Field<int>("Id")).ToArray();
i
来自哪里?您正在使用foreach,因此不需要计数器变量。您的循环应该如下所示:

foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr.Field<string>("Status") == "Active") {
        ...
    }
}
List<int> promotionLst = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr["Status"].ToString() == "Active") {
        promotionLst.Add(Convert.ToInt32(dr["Id"]));
    }
}
int[] promotion = promotionLst.ToArray();
…是使用一个值创建一个新数组(丢弃其中的所有内容),该值是当前记录的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"));
    }
}

你会想要这样的东西:

foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr.Field<string>("Status") == "Active") {
        ...
    }
}
List<int> promotionLst = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr["Status"].ToString() == "Active") {
        promotionLst.Add(Convert.ToInt32(dr["Id"]));
    }
}
int[] promotion = promotionLst.ToArray();
List promotionLst=new List();
foreach(ds.Tables[0].行中的数据行dr){
如果(dr[“状态”].ToString()=“活动”){
promotionLst.Add(转换为32(dr[“Id”]);
}
}
int[]promotion=promotionLst.ToArray();

这对我来说是一个全新的概念:)
List<int> promotionLst = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr["Status"].ToString() == "Active") {
        promotionLst.Add(Convert.ToInt32(dr["Id"]));
    }
}
int[] promotion = promotionLst.ToArray();