After making a search to a SharePoint site, it isn't always easy to get a reference to each item returned in the search. This is because we don't know the Web and List where each item is located. The following example shows how this can be achieved:
class SiteCollectionSearch
{
/// <summary>
/// Search items by title
/// </summary>
/// <param name="web"></param>
/// <returns></returns>
private static DataTable Search(SPWeb web)
{
//search items by title
StringBuilder query = new StringBuilder();
query.Append("<Where>");
query.Append("<Contains>");
query.Append("<FieldRef Name='Title' />");
query.Append("<Value Type='Text'>SharePoint</Value>");
query.Append("</Contains>");
query.Append("</Where>");
query.RowLimit = 100;
SPSiteDataQuery query = new SPSiteDataQuery();
query.Webs = "<Webs Scope='SiteCollection' />";
spQuery.Query = query.ToString();
//perform the search
DataTable searchResults = web.GetSiteData(query);
//return results - since ViewFields property is not specified in
//the query, WebId, ListId and Item Id are automatically returned
return searchResults;
}
/// <summary>
/// After a search, obtains each item by its Id.
/// </summary>
/// <param name="list"></param>
private static void GetItemsByID()
{
SPSite site = new SPSite("http://portal");
using (SPWeb web = site.OpenWeb())
{
//search documents by title
using (DataTable docs = Search(web))
{
//iterate results
foreach (DataRow row in docs.Rows)
{
//get webId of the current item
Guid webId = new Guid(Convert.ToString(row["WebID"]));
//get listId of the current item
Guid listId = new Guid(Convert.ToString(row["ListID"]));
//get id of the current item
int itemId = Convert.ToString(row["ID"]);
//get the web where the item is located
using (SPWeb itemWeb = site.AllWebs[webId])
{
//get list using the list id
SPList list = itemWeb.Lists[listId];
SPListItem listItem = null;
try
{
//get item using its id
listItem = list.Items[itemId];
}
catch { }
if (listItem != null)
{
//do something with the item. Example:
//update the title
listItem["Title"] = listItem["Title"]
+ " Updated";
listItem.Update();
}
}
}
}
}
}
}
In the previous example, the following actions are being performed:
- A search is performed to entire site collection for documents containing the word "SharePoint". As a result of that search, a DataTable instance is returned containing the search results;
- Each row of the search results is iterated. For each row, three important values are obtained: the item's ID, ListId and WebId. These are obtained automatically in the result of a SPSiteDataQuery when the ViewFields property is not set;
- The SPWeb instance where the item is located is obtained using the previously obtained WebId;
- The SPList instance where the item is located is obtained using the previously obtained ListId;
- The SPListItem is obtained from the list using the item's ID;
- Finally, something is done with the item. For example, updating its title.