Get SPListItem field values using CAML query

I needed to query lists, and return values/data from a single column... a lot... so I wrote a function to do this for me. Instead of writing the CAML for each call, I used dictionaries to store the conditions, and generate the CAML dynamically.

Here's the code to build the CAML, perform the query, and return the results...

NOTE: see [link TBD] as an updated alternative, using LINQ to generate the CAML query.
Language:
C#
Keywords:
SharePoint; CAML
Code Snippet

public static List<object> GetSPList_FieldObjectsCAML(string SiteURL, string WebPath, GUID ListGUID, string FieldName, Dictionary<string, KeyValuePair<string, string>> ConditionFieldValues)
{
    List<object> outval = new List<object
>();

    using (SPSite tSite = new SPSite(SiteURL))
    {
        using (SPWeb
tWeb = tSite.OpenWeb(WebPath))
        {
            SPList
tList = tWeb.Lists[ListGUID];
            string QueryStr = "<Where>"
;

            for
(int
i = 0; i < ConditionFieldValues.Count - 1; i++)
                QueryStr +=
"<And>";

            bool isFirst = true;
            foreach (KeyValuePair<string, KeyValuePair<string, string>> item in ConditionFieldValues)
            {
                if (String.IsNullOrEmpty(item.Value.Value))
                    QueryStr +=
"<IsNull><FieldRef Name='" + item.Key + "' /></IsNull>";
                else
                    QueryStr += "<Eq><FieldRef Name='" + item.Key + "' /><Value Type='" + item.Value.Key + "'>" + item.Value.Value + "</Value></Eq>";

                if (!isFirst)
                    QueryStr +=
"</And>";

                if (isFirst)
                    isFirst =
false;
            }
            QueryStr +=
"</Where>";

            foreach (SPListItem tItem in tList.GetItems(new SPQuery() { Query = QueryStr }))
            {
                if (tItem[FieldName] == null)
                    continue;

                outval.Add(tItem[FieldName]);
            }

        }
// using tWeb
    } // using tSite

    return outval;
}

Example

Dictionary<string, KeyValuePair<string, string>> conditions = new Dictionary<string, KeyValuePair<string, string>>
  {
    { TypeFieldName,
new KeyValuePair<string, string>("Lookup", IssueType) },
    { LocationFieldName,
new KeyValuePair<string, string>("Lookup", Location) }
  };

List<object> Readers = GetSPList_FieldObjectsCAML(ListPath, ListReadersFieldName, conditions);


Created 2012-02-11
comments powered by Disqus
Login