从数据集中添加到 int 数组
我必须将状态值与“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”的公共定义
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议使用 LINQ:
如果您想修复代码,让我告诉您它有什么问题:
i
来自哪里?您正在使用foreach
,因此不需要计数器变量。您的循环应如下所示:现在,如何将 Id 添加到数组中。您在这里所做的...
...是创建一个带有一个值的新数组(丢弃其中的所有内容),该值是当前记录的 Id。数组不是添加项目的良好数据结构。我建议使用 List:
如果您仍然需要数组,可以稍后将其转换:
I suggest to use LINQ:
If you want to fix your code instead, let me tell you what's wrong with it:
Where does the
i
come from? You're usingforeach
, so you don't need a counter variable. Your loop should look like this:Now, how to add the Id to the array. What you are doing here...
...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:
If you still need an array, you can convert it afterwards:
你会想要这样的东西:
You'll want something like this:
不能在 foreach 循环中使用过滤条件。试试这个:
这可以解决您问题的错误部分,但是您对
promotionID
的使用看起来不正确,因为您在每个正面匹配上都覆盖了它。您应该使用List
而不是int[]
并使用promotion.Add(Convert.ToInt32(dr["Id"])) 将号码添加到列表中。看起来像:
另一个选择是 LINQ,正如 Heinzi 演示的。
You can't use a filter condition in the foreach loop. Try this:
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 aList<int>
instead ofint[]
and usepromotion.Add(Convert.ToInt32(dr["Id"]))
to add numbers to the list. That looks like:Another option is LINQ as Heinzi demonstrated.