Returning items from a SharePoint list is very simple task so this article is going to be one of the shortest I have written. You can use GetItemById() method to return a single list item or GetItems(CamlQuery) to return multiple items. CAML or Collaborative Application Markup Language is an XML-based language that is used to define the fields and views that are used in sites and lists. Passing an undefined CamQuery object to the GetItems method will return all of the items in the list.

The next code is using CamlQuery to filter all of the items that have the value 23 in the column named Years.

x
1
using (SPSite site = new SPSite("http://spf2010/sites/dev"))
2
{
3
    using (SPWeb web = site.OpenWeb("MyDevSite"))
4
    {
5
        SPFolder folder = web.Folders["DevList"];
6
        SPQuery query = new SPQuery();
7
        query.Query = "<Where>" +
8
                          "<Eq>" + 
9
                              "<FieldRef Name='Years' />" +
10
                              "<Value Type='Number'>23</Value>" +
11
                          "</Eq>" +
12
                       "</Where>";
13
14
        SPDocumentLibrary list = folder.DocumentLibrary;
15
        SPListItemCollection items = list.GetItems(query);
16
    }
17
}

At the end the local variable items contains all of the list items that meet the specified criteria. In my case I created a datatable with the items and showed the result in a gridview.

SPQuery is using the internal names of the columns. Every SharePoint field have two kinds of names, DisplayName and InternalName. When you create a new list it comes with predefined columns and one of them is Title. You can choose to rename the column to something more fancy but the internal name will stay the same.

One of my columns that I wanted to use to filter the items was created using Cyrillic alphabet so the InternalName contained special hex codes. The easiest way for me to find the InternalName was to open the list and click the required column name to sort the items in the list. Then I just checked the query string and looked for the parameter SortField and copy its value. Empty space in the internal name is also converted to hex code (_x0020_).