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 Comments

  1. John Fortnership says:

    Good Tip! Didn’t know you could do this without a typed iteration through the listitem collection.

  2. James Forker says:

    This is a pretty good tip. Thanks a lot for the post. Could probably cut down on some foreach loops I have running internally

  3. Steve Christopherson says:

    Nice refactoring!

Leave a Reply

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