GetItems method (SPQuery)

SPList.GetItems method (SPQuery)

Gets a collection of items from the list based on the specified query.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public SPListItemCollection GetItems(
	SPQuery query


Type: Microsoft.SharePoint.SPQuery

The query that is used to retrieve list items.

Return value

Type: Microsoft.SharePoint.SPListItemCollection
The list items that satisfy the query.

The following example is a console application that gets a collection of items from the Tasks list and prints a report to the console.

using System;
using Microsoft.SharePoint;

namespace Test
   class ConsoleApp
      static void Main(string[] args)
         using (SPSite site = new SPSite("http://localhost"))
            using (SPWeb web = site.OpenWeb())
               // Build a query.
               SPQuery query = new SPQuery();
               query.Query = string.Concat(
                                 "<FieldRef Name='Status'/>",
                                 "<Value Type='CHOICE'>Not Started</Value>",
                                 "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                 "<FieldRef Name=’Priority’ Ascending='TRUE' />", 

               query.ViewFields = string.Concat(
                                   "<FieldRef Name='AssignedTo' />",
                                   "<FieldRef Name='LinkTitle' />",
                                   "<FieldRef Name='DueDate' />",
                                   "<FieldRef Name='Priority' />");

               query.ViewFieldsOnly = true; // Fetch only the data that we need.

               // Get data from a list.
               string listUrl = web.ServerRelativeUrl + "/lists/tasks";
               SPList list = web.GetList(listUrl);
               SPListItemCollection items = list.GetItems(query);

               // Print a report header.
               Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                  "Assigned To", "Task", "Due Date", "Priority");

               // Print the details.
               foreach (SPListItem item in items)
                  Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                     item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
© 2015 Microsoft