When querying a list in SharePoint, the SPList.GetItems method is a simple and relatively easy way to return a list of records from the SharePoint List (returned as a SPListItemCollection). This is implemented simply as follows:
using (SPWeb currentWeb = currentSite.OpenWeb(_RelativeWebUrl))
{
SPList currentList = currentWeb.Lists[_ListName];
SPListItemCollection items = currentList.GetItems();
}
As you progress a bit, you will find that you won’t necessarily want to return all the items in a list. That’s when using the SPQuery object comes in real handy. Simply write the CAML query for the code that you wish to return, then pass the SPQuery object to the GetItems method. This should then return the exact subset of data that you were after. (
using (SPWeb currentWeb = currentSite.OpenWeb(_RelativeWebUrl)) { SPList currentList = currentWeb.Lists[_ListName]; SPQuery query = new SPQuery(); query.Query = String.Format("<Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"{1}\">{2}</Value></Eq></Where>",_InternalName, _Type,_Value); SPListItemCollection items = currentList.GetItems(query); }
HOWEVER, you must be careful that you write your CAML code correctly, or the method will return all records! This really surprised me and is a strange ‘feature’ one would think – I personally would have thought this should have returned NO records if it the query was incorrect. So basically if you find that every time you run a query there is a full record set returning, then check your CAML query…
For testing or writing your CAML queries, I would recommend downloading and trying out the U2U CAML Query Builder – this is a great little tool.