27 08 2013
A Very Damned-Useful Extension Method
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(); |
Enjoy!
Programmatically Set ” Allow this site to appear in search results?” Supporting Office 365 Customisations
Nice. The continuation of this, of course, is to allow comparison operators other than equals. Then you could add value types other than text (datetime, integer, etc…). Then you could add lookups. Before you know it, you will have a simple to use CAML interpreter for C#. 🙂
In deed really good to know. !
Yesterday I built myself a little function in JavaScript to generate a CAML clause from an array of values.
e.g.,
Two things surprise me about that:
1) Why it took me so long, since I’ve done this many times, and
2) Why .NET developers don’t seem to have a huge library out there somewhere that does this stuff for them. Sort of like SPServices for .NET. Or is there one?
That’s probably because we always just Google for the code to do the tihng we need to do, and we paste it in.
I’ve been reducing code wastage in a couple of projects, and I’m hoping to create a single Utility library that we maintain internally for use on any project.
Depending on what kind of stuff ends up in there, I think it could become a community release, including things to do simple stuff like adding web parts to pages, creating Publishing pages, etc.
@Marc do you already know of this excellent javascript library that simplifies the creation of CAML queries?
here i have some extension methods.
http://www.codingsack.com/2016/01/17/bunch-of-useful-extension-methods/