Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to CheckBoxList data items

Im using LINQ to retrive cheched Items from CheckBoxList control:

Here the LINQ :

    IEnumerable<int> allChecked = (from ListItem item in CheckBoxList1.Items
                                       where item.Selected 
                                       select int.Parse(item.Value));

My question is why item have to be ListItem type?

like image 969
Michael Avatar asked Jan 18 '23 19:01

Michael


2 Answers

The CheckedListBox was created before generics were introduced, thus the Items collection returns objects rather than the strongly typed ListItem. Luckily, fixing this with LINQ is relatively easy using the OfType() (or Cast) methods:

IEnumerable<int> allChecked = (from ListItem item in CheckBoxList1.Items.OfType<ListItem>()
                                   where item.Selected  
                                   select int.Parse(item.Value)); 
like image 95
Jim Wooley Avatar answered Jan 28 '23 17:01

Jim Wooley


My question is why item have to be ListItem type?

Because CheckBoxList1.Items is an ObjectCollection whose members are ListItems. That's what your linq query is working against.

like image 24
Adam Rackis Avatar answered Jan 28 '23 15:01

Adam Rackis