Pankaj
Pankaj

Reputation: 10095

Checklist Box Selected Items from LinQ

I am writing the following line of code to extract the selected items in checklistbox.

ListItemCollection ChecklistBoxCollection = new ListItemCollection();
            foreach (ListItem ChecklistBoxItem in ChecklistBox.Items)
                if (ChecklistBox.Selected)
                    ChecklistCollection.Add(ChecklistBox);

Is there any way to get these items in LinQ?

Upvotes: 0

Views: 728

Answers (2)

tvanfosson
tvanfosson

Reputation: 532445

There's no automatic conversion to ListItemCollection, but you can use AddRange to add the selected items at once. I'm not sure this is much of an improvement and may be slower because AddRange only takes an array.

ListItemCollection ChecklistBoxCollection = new ListItemCollection();
ChecklistBoxCollection.AddRange( checklistBox.Items
                                             .Cast<ListItem>()
                                             .Where( i => i.Selected )
                                             .ToArray() );

Upvotes: 1

codeandcloud
codeandcloud

Reputation: 55200

I have been using these extension methods.

    public static List<string> GetCheckedValues(this CheckBoxList list)
    {
        var values = new List<string>();
        values.AddRange(from ListItem item in list.Items
                    where item.Selected
                    select item.Value);
        return values;
    }

    public static List<string> GetCheckedTexts(this CheckBoxList list)
    {
        var values = new List<string>();
        values.AddRange(from ListItem item in list.Items
                    where item.Selected
                    select item.Text);
        return values;
    }

Upvotes: 0

Related Questions