我需要在int[]
数组中存储不同数量的值,具体取决于从我的CheckboxList
控件(cblSections
)中选择了多少个项目。在int []对象中存储不同数量的值
目前我将这些值存储在ArrayList
中,然后确定此对象的长度,并根据此对象设置我的int[]
对象的大小。
有没有更好的方式来做到这一点,这涉及到更少的代码(和更少的对象!)?
ArrayList alSectionId = new ArrayList();
foreach (ListItem item in cblSections.Items) {
if (item.Selected) {
alSectionId.Add(item.Value);
}
}
int[] sectionId = new int[(alSectionId.Count - 1) + 1];
if (alSectionId.Count > 0) {
int i = 0;
foreach (int sId in alSectionId) {
sectionId[i] = sId;
i += 1;
}
}
任何理由你最终需要一个'int []'而不是'列表'?任何你使用'ArrayList'而不是'List '的原因? –
2012-07-31 10:06:18
@JonSkeet'int []'是模型中使用的数据类型,但是如果'List'是一个更好的选择,这个可以改变?我实际上是在VB.NET中编写这段代码,所以之后将任何东西都转换回来,但我更愿意学习C#的方式。 –
Curt
2012-07-31 10:08:16
你只能使用ArrayList对象来计算int数组的大小吗? – SMK 2012-07-31 10:08:19