I need to store different quantities of values in an int[] array, depending on how many items have been selected from my CheckboxList control (cblSections).
At the moment I’m storing these values in an ArrayList, then determining the length of this object, and setting the size of my int[] object dependant on that.
Is there a better way of doing this, which involves less code (and less objects!)?
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;
}
}
You should use the
Listobject instead. Then once you have populated this you can covert it directly to anint[]using theToArray()function:NOTE: Although the
ArrayListclass does also seem to have aToArray()function, it is better to useListanyway… why? I have no idea, it’s one of those things I have heard so many times that I just take it for granted and forget the original reason why :/