27 08 2013
Trying never to use SPList.Items (due to Best Practice), yet needing to grab some items from a list quite often? Here’s an extension method which I use a fair bit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/// <summary> /// Gets items where a property matches a value /// </summary> /// <param name="list">The list.</param> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <returns>A list collection of SPListItems</returns> public static IList<SPListItem> ItemsWhere(this SPList list, string property, string value) { SPQuery query = new SPQuery(); query.Query = string.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", property, value); SPListItemCollection items = list.GetItems(query); return items.Cast<SPListItem>().ToList(); } |
You can then use regular LINQ queries to get the item or items you need against the object returned by this, for example:
1 2 |
SPList webPartCatalog = site.GetCatalog(SPListTemplateType.WebPartCatalog); SPListItem wpItem = webPartCatalog.ItemsWhere("FileLeafRef", "Some Web Part.dwp").FirstOrDefault(); |
[…]