views:

1480

answers:

2

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?

+17  A: 

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.

Andrew Hare
Thanks Andrew. I learned something today from your answer, so thank you. I'll mark this as the 'answer' although now I am questioning myself which is more readable to the developer. Thanks again!
p.campbell
+5  A: 

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.

Jon Skeet
Thanks Jon. I have used this implicit cast as an enhancement to my query.
p.campbell