Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to int array from dataset

Tags:

c#

ado.net

I have to add all the Id from the dataset that has Status value same as "Active" to the int array PromotionID. How is that possible. What am i missing?

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

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

The error is:

foreach statement cannot operate on variables of type 'bool' because 'bool' does not contain a public definition for 'GetEnumerator'

like image 814
challengeAccepted Avatar asked Dec 17 '22 19:12

challengeAccepted


1 Answers

I suggest to use LINQ:

int[] promotionIDs = (from dr in ds.Tables[0].AsQueryable()
                      where dr.Field<string>("Status") == "Active"
                      select dr.Field<int>("Id")).ToArray();

If you want to fix your code instead, let me tell you what's wrong with it:

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

Where does the i come from? You're using foreach, so you don't need a counter variable. Your loop should look like this:

foreach (DataRow dr in ds.Tables[0].Rows) {
    if (dr.Field<string>("Status") == "Active") {
        ...
    }
}

Now, how to add the Id to the array. What you are doing here...

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

...is to create a new array (throwing away everything that was in it) with one value, which is the Id of the current record. Arrays are not good data structures for adding items. Let me suggest to use a List instead:

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"));
    }
}

If you still need an array, you can convert it afterwards:

int[] promotionIDArray = promotionIDs.ToArray();
like image 118
Heinzi Avatar answered Jan 06 '23 08:01

Heinzi