Reputation: 103348
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;
}
}
Upvotes: 0
Views: 101
Reputation: 48415
You should use the List
object instead. Then once you have populated this you can covert it directly to an int[]
using the ToArray()
function:
List<int> items = new List<int>();
items.ToArray();
NOTE: Although the ArrayList
class does also seem to have a ToArray()
function, it is better to use List
anyway... 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 :/
Upvotes: 1
Reputation: 129792
You could use:
int numSelected = cblSections.Items.Count(x => x.Selected);
You would also be able to produce your array immediately:
int[] sectionId = cblSections.Items
.Where(x => x.Selected)
.Select(x => x.Value)
.ToArray();
Upvotes: 6