I like to use linq to find, sort, .. items in a list quick and easily, but it’s a pain to convert a SPListItemCollection into a generic list. Today I wrote a class that do the conversion for me easily.
Code Snippet
- public class SPListItemCollectionAdapter : List<SPListItem>
- {
- private SPListItemCollection _listItemCollection;
- /// <summary>
- /// Get a generic list of SPListItems and convert it
- /// </summary>
- /// <param name="listItemCollection">SPListItemCollection collection of items</param>
- public SPListItemCollectionAdapter(SPListItemCollection listItemCollection)
- {
- _listItemCollection = listItemCollection;
- Refresh();
- }
- /// <summary>
- /// Convert a SPListItemCollection into a generic list
- /// </summary>
- private void Refresh()
- {
- this.Clear();
- foreach (SPListItem item in _listItemCollection)
- {
- this.Add(item);
- }
- }
- }
Now you can use the class above like:
Code Snippet
- private SPListItemCollectionAdapter GetItems(SPList list, string query)
- {
- SPQuery q = new SPQuery();
- q.Query = query;
- return new SPListItemCollectionAdapter(list.GetItems(q));
- }
The only thing you need to do is declare a variable of the type SPListItemCollectionAdapter and create a new one.
Isn’t it easy?
I generally prefer .Cast() on the collection.
BeantwoordenVerwijderen