Getting Selected ListItem’s Using LINQ

I had a friend just show me this really simple way when you are employing a ListBox control and want to get the ListItem.Selected items using LINQ in strongly typed collection to execute FirstOrDefault() etc.

Simply use:

As a lambda expression:

[csharp]

var box = new ListBox();
var selectedItems = box.Items.Cast().Where(li => Equals(li.Selected, true));

[/csharp]

As a statement:

[csharp]

var box = new ListBox();
var selectedItems = box.Items.Cast().Where(li => { return Equals(li.Selected, true); });

[/csharp]

Really simple!

Share

3 thoughts on “Getting Selected ListItem’s Using LINQ”

Leave a Reply

Your email address will not be published. Required fields are marked *