Querying Selected Items From ListItemCollection Using Lambda Expressions
27 May 2008You can use Lambda expressions and the new extensions provided in the .NET framework 3.5 to filter your specialized collections like the ListItemCollection (used in ASP.NET ListBox controls).
I found this great usage for lambda this weekend when posed with a problem using a ListBox control with a SelectionMode of Multiple. If you’ve ever worked with the ListBox before (and I think you have), getting the single SelectedValue or SelectedIndex is a piece of cake. When you need to get all the selected items, well now you’re probably thinking about using a foreach loop to find the selected items, list this:
Two ‘old school’ solutions to get Selected items from a ListItemCollection
Simple foreach loop for finding Selected items in a ListItemCollection
List<ListItem> selectedItems = new List<ListItem>();
foreach (ListItem itm in lboxItems.Items)
{
if (itm.Selected)
selectedItems.Add(itm);
}
Or you’re thinking about using an Iterator pattern here, made easy with .NET framework 2.0 and the lovely generics it brought us:
More advanced Iterator patten for returning only selected items
private IEnumerable<ListItem> selectedItems(ListBox lbox)
{
foreach (ListItem itm in lbox.Items)
{
if (itm.Selected)
yield return itm;
}
}
Welcome to Lambda and .NET framework 3.5 !!!
Can you tell that I am overly excited about this?
So there is two more ways to do this:
How to get only the selected items from a ListBox control using Linq
var selectedItems = from li in lboxItems.Items.Cast<ListItem>()
where li.Selected == true
select li;
You see we have to first Cast the specialized ListItemCollection to a generic List<ListItem> collection before it can be used in a Linq query (for more info on linq this book really helped me on the subject). You may even want to finally encapsulate the (from …. select li) with parenthesis and then apply a .ToList(), that way it will be typed as a Generic List<ListItem> collection.
How to get only the selected items from a ListBox control using Lambda Expressions
List<ListItem> selectedItems =
lboxItems.Items.Cast<ListItem>()
.Where(itm => itm.Selected == true).ToList();
You see we also had to first Cast the specialized ListItemCollection to a generic List<ListItem> collection first to get the extensions (Where and ToList) … now in the Where method is the place that we finally see the lambda expression come to light, this basically is an easier way to express an anonymous delagate function, if you’ve never used one before, then feel lucky that your here now with the availablility of lambda!!!
You can download a working Lamda demo against ListItemCollection here
I highly recommend ASP.NET 3.5 Unleashed which talks a lot about Linq and Lamda expressions.
No comments yet
Leave a Reply
You must be logged in to post a comment.
