Company      |       Articles & Research      |      Services      |      Software      |      Contact

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:

C#:
  1. var box = new ListBox();
  2. var selectedItems = box.Items.Cast<ListItem>().Where(li => Equals(li.Selected, true));

As a statement:

C#:
  1. var box = new ListBox();
  2. var selectedItems = box.Items.Cast<ListItem>().Where(li => { return Equals(li.Selected, true); });

Really simple!

share save 171 16 Getting Selected ListItems Using LINQ

Related posts:

  1. Best Practice: Don’t Iterate SPListItems for IQueryable Support
  2. Why CommaDelimitedStringCollection Made Me Happy Today
  3. Use LINQ To Get Central Administration Web Applications
  4. Can’t Use Resharper 4.5 With LINQ-To-XSD
  5. Generating Columns For An SPGridView With LINQ (Extension Method)

3 Comments »

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

    Comment by John Fortnership — September 8, 2009 @ 10:08 am

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

    Comment by James Forker — September 8, 2009 @ 10:10 am

  3. Nice refactoring!

    Comment by Steve Christopherson — September 8, 2009 @ 8:46 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment