LINQ: Get all selected values of a CheckBoxList using a Lambda expression

Consider a scenario where you want to retrieve a List or IEnumerable of the values of all the selected checkboxes in an <asp:CheckBoxList>.

Here’s the current implementation:

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

Question: How would you improve this LINQ query using a lambda expression or lambda syntax?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are using lambda expressions – they are just concealed by your use of C#’s query operators.

Consider that this:

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

Gets compiled to this:

IEnumerable<int> allChecked = chkBoxList.Items.Cast<ListItem>()
                              .Where(i => i.Selected)
                              .Select(i => int.Parse(i.Value));

As you can see you are already using two lambda expressions (they are the parameters to the Where and Select methods) and you didn’t even know it! This query is fine and I wouldn’t change it at all.

Method 2

I would improve the query expression by making the call to Cast<T> implicit:

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

When you specify the type of a range variable, the compiler inserts a call to Cast<T> for you.

Other than that, I entirely agree with Andrew.

EDIT: For GONeale:

IEnumerable<int> allChecked = chkBoxList.Items
                                        .Cast<ListItem>()
                                        .Where(item => item.Selected)
                                        .Select(item => int.Parse(item.Value));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x