0

我需要在一个数组中存储不同数量的值,具体取决于从我的控件 ( )int[]中选择了多少项目。CheckboxListcblSections

目前我将这些值存储在一个 中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;
    }
}
4

2 回答 2

6

你可以使用:

int numSelected = cblSections.Items.Count(x => x.Selected);

您还可以立即生成您的数组:

int[] sectionId = cblSections.Items
    .Where(x => x.Selected)
    .Select(x => x.Value)
    .ToArray();
于 2012-07-31T10:05:04.350 回答
1

您应该改用该List对象。然后,一旦您填充了它,您就可以将其直接转换为int[]使用该ToArray()函数:

List<int> items = new List<int>();
items.ToArray();

注意:虽然这个ArrayList类似乎也有一个ToArray()功能,但最好还是使用List......为什么?我不知道,这是我听过很多次的事情之一,我只是认为这是理所当然的,忘记了最初的原因:/

于 2012-07-31T10:08:46.657 回答