Using Linq to Find Items Selected In ListBox

If you are trying to find items selected in a ListBox, you could do it the old fashioned way by looping through list items and checking to see if item is selected and if the item is selected you grab the selected value and create an instance of the object, assign the selected value to the object and add the object to the collection. However a simple query makes this entire process only 1 liner. Here is the code that I used to grab selected items from a ListBox.

ListBox box = e.Item.FindControl("skus") as ListBox;
            var items =
            box.Items.Cast<ListItem>()
            .Where(item => item.Selected)
            .Select(item => new FeaturedProduct { Sku = item.Value });
           

In the above code, I am first casting Items property to a collection of ListItems and filtering it to items that are selected and than for each selected list item, I am creating an instance of a FeaturedProduct object. So in the end, I end up with a collection of FeaturedProducts.

No Comments