Add to int array from dataset
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[]开发者_如何学Python 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'
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();
You'll want something like this:
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();
You can't use a filter condition in the foreach loop. Try this:
int[] promotion;
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["Status"].ToString() == "Active")
promotionID = new int[] { Convert.ToInt32(dr["Id"]) };
}
That takes care of the error portion of your question, however your use of promotionID
looks incorrect since you're overwriting it on each positive match. You should use a List<int>
instead of int[]
and use promotion.Add(Convert.ToInt32(dr["Id"]))
to add numbers to the list. That looks like:
var promotion = new List<int>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["Status"].ToString() == "Active")
promotion.Add(Convert.ToInt32(dr["Id"]));
}
Another option is LINQ as Heinzi demonstrated.
精彩评论