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#:
-
var selectedItems = box.Items.Cast<ListItem>().Where(li => Equals(li.Selected, true));
As a statement:
C#:
-
var selectedItems = box.Items.Cast<ListItem>().Where(li => { return Equals(li.Selected, true); });
Really simple!
Related posts:
- Best Practice: Don’t Iterate SPListItems for IQueryable Support
- Why CommaDelimitedStringCollection Made Me Happy Today
- Use LINQ To Get Central Administration Web Applications
- Can’t Use Resharper 4.5 With LINQ-To-XSD
- Generating Columns For An SPGridView With LINQ (Extension Method)
3 Comments »
RSS feed for comments on this post. TrackBack URL























Articles & Research
SharePoint Architecture
Research Methodology
Personal/Off-Topic
Article Or Research Filed Under 

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
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
Nice refactoring!
Comment by Steve Christopherson — September 8, 2009 @ 8:46 pm