Combine List View and CAML Query string in SPQuery

There is a need sometimes to combine a physical list view (on a SharePoint list) with a custom CAML query when retrieving the data in the SharePoint object model. Most of you probably know that there is an overload of the SPList.GetItems() method which takes a SPQuery and a View Guid as the parameters, but most of the time you don’t know the Guid of the View on the target system, and honestly, you nether want to store it to the configuration list, nor to search for it in the code.

Luckily, there is a (not so obvious) way to do it through the SPQuery, and then to pass only the SPQuery to the GetItems() method:


string query = "<Where><Eq><FieldRef Name="ID" /><Value Type="Counter">1</Value></Eq></Where>";

SPList citiesList = web.Lists["MyList"];

SPView view = citiesList.Views["MyView"];

SPQuery qry = new SPQuery(view);

qry.Query = query;

SPListItemCollection items = citiesList.GetItems(qry);

In this example, a SPListItem with ID 1 will be returned from the “MyList” (note the CAML query), but only the fields which are defined by the view “MyView” will be in the┬áresult set. Quite usefull.

PS. Note how the GetItem() method parameter is called “viewName”, even if they really wanted to say “View Guid”. Oh, what the heck, name, guid, id, whatever, all the same in the SharePoint world. You just have to love Microsoft for this one… ­čśë
http://msdn.microsoft.com/en-us/library/ms434064.aspx