如何:检索列表项
上次修改时间: 2011年4月29日
适用范围: SharePoint Foundation 2010
本文内容
从列表检索项
使用 Include 方法
从指定数目的项中检索特定字段
检索网站上所有列表中的项
使用列表项集合位置检索项
若要返回列表中的项,可使用 GetItemById() 方法 (JavaScript: getItemById(id)) 返回单个项,也可使用 GetItems(CamlQuery) 方法 (JavaScript: getItems(query)) 返回多个项。然后可以使用 Load<T>(T, []) 方法 (JavaScript: load(clientObject)) 获取代表这些项的列表项对象。
从列表检索项
GetItems(CamlQuery) 方法 (JavaScript: getItems(query)) 允许您定义协作应用程序标记语言 (CAML) 查询,以指定要返回哪些项。您可以传递一个未定义的 CamlQuery 对象 (JavaScript: CamlQuery) 以返回列表中的所有项,也可以使用 ViewXml 属性 (JavaScript: viewXml) 定义一个 CAML 查询并返回符合特定条件的项。
以下示例显示 Announcements 列表中前 100 项的 ID 以及 Title 和 Body 列值,从集合 ID 大于 10 的列表项开始。
using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointServices.Samples
{
class RetrieveListItems
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]);
}
}
}
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Namespace Microsoft.SDK.SharePointServices.Samples
Class RetrieveListItems
Shared Sub Main ()
Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
Dim clientContext As New ClientContext(siteUrl)
Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")
Dim camlQuery As New CamlQuery()
camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + _
"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"
Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)
clientContext.Load(collListItem)
clientContext.ExecuteQuery()
Dim oListItem As ListItem
For Each oListItem In collListItem
Console.WriteLine("ID: {0} " + ControlChars.Lf + "Title: {1} " + _
ControlChars.Lf + "Body: {2}", oListItem.Id, _
oListItem("Title"), oListItem("Body"))
Next oListItem
End Sub
End Class
End Namespace
var siteUrl = '/sites/MySiteCollection';
function retrieveListItems() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\nTitle: ' + oListItem.get_item('Title') +
'\nBody: ' + oListItem.get_item('Body');
}
alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
上面的示例加载由 CAML 查询指定的项的集合,并且以后可以访问返回的每个列表项对象上的所有默认属性。使用 Include<TSource>(IQueryable<TSource>, []) 方法可指定可用的属性,以限制通过查询返回的数据量,从而提高性能。在 ECMAScript(JavaScript、JScript) 中,可指定将 Include 语句作为传递给 load(clientObject) 方法的查询字符串的一部分。
使用 Include 方法
默认情况下,在返回列表项时,ListItem (JavaScript: ListItem) 的以下四个属性不可用:DisplayName (JavaScript: displayName)、EffectiveBasePermissions (JavaScript: effectiveBasePermissions)、HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments) 和 RoleAssignments (JavaScript: roleAssignments)。如果您尝试访问其中某个属性,上面的示例将返回 PropertyOrFieldNotInitializedException。若要访问这些属性,请在 LINQ 查询表达式内使用 Include<TSource>(IQueryable<TSource>, []) 方法明确返回这些属性。在 ECMAScript(JavaScript、JScript) 中,可指定将 Include 作为查询字符串的一部分。有关非默认属性的详细信息,请参阅数据检索概述。
若要修改上面的示例使其返回 DisplayName (JavaScript: displayName) 和 HasUniqueRoleAssignments (JavaScript: hasUniqueRoleAssignments) 的值,可以将前面对 Load<T>(T, []) 方法 (JavaScript: load(clientObject)) 的调用替换为使用 LINQ 查询的调用,后者用 C# 编写,并且需要引用 System.Linq 命名空间。在 ECMAScript(JavaScript、JScript) 中,指定 Include。
备注
当您使用 LINQ 针对客户端对象模型创建查询时,需使用 LINQ to Objects 而不是 LINQ to SharePoint 提供程序,只有在对服务器对象模型编写代码时,才能使用 LINQ to SharePoint 提供程序。
using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointServices.Samples
{
class RetrieveListItemsInclude
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem,
items => items.Include(
item => item.Id,
item => item.DisplayName,
item => item.HasUniqueRoleAssignments));
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
Console.WriteLine("ID: {0} \nDisplay name: {1} \nUnique role assignments: {2}",
oListItem.Id, oListItem.DisplayName, oListItem.HasUniqueRoleAssignments);
}
}
}
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Namespace Microsoft.SDK.SharePointServices.Samples
Class RetrieveListItemsInclude
Shared Sub Main ()
Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
Dim clientContext As New ClientContext(siteUrl)
Dim oList As List = clientContext.Web.Lists.GetByTitle("Announcements")
Dim camlQuery As New CamlQuery()
camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>"
Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)
clientContext.Load(collListItem, _
Function(items) items.Include( _
Function(item) item.Id, _
Function(item) item.DisplayName, _
Function(item) item.HasUniqueRoleAssignments))
clientContext.ExecuteQuery()
Dim oListItem As ListItem
For Each oListItem In collListItem
Console.WriteLine("ID: {0} " + ControlChars.Lf + _
"Display name: {1} " + ControlChars.Lf + _
"Unique role assignments: {2}", oListItem.Id, _
oListItem.DisplayName, oListItem.HasUniqueRoleAssignments)
Next oListItem
End Sub
End Class
End Namespace
var siteUrl = '/sites/MySiteCollection';
function retrieveListItemsInclude() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Id, DisplayName, HasUniqueRoleAssignments)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\nDisplay name: ' + oListItem.get_displayName() +
'\nUnique role assignments: ' + oListItem.get_hasUniqueRoleAssignments();
}
alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
由于该示例使用了 Include<TSource>(IQueryable<TSource>, []) 方法(在 ECMAScript(JavaScript、JScript) 中为 Include),因此在执行查询后,只能访问指定的属性。因此,如果您尝试访问这些指定属性以外的其他属性,将会收到 PropertyOrFieldNotInitializedException。此外,如果您尝试使用 ContentType (JavaScript: contentType) 或 ParentList (JavaScript: parentList) 等属性来访问包含对象的属性,也会收到此错误。
从指定数目的项中检索特定字段
以下示例演示如何只从列表中的前五项中检索特定字段。由于仅指定了 Title 和 Body 列,因此只能访问这两个属性。
using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointServices.Samples
{
class RetrieveSpecificItemsFields
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
CamlQuery camlQuery = new CamlQuery();
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(
collListItem,
items => items.Take(5).Include(
item => item["Title"],
item => item["Body"]));
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
Console.WriteLine("Title: {0} \nBody: {1}\n", oListItem["Title"], oListItem["Body"]);
}
}
}
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Namespace Microsoft.SDK.SharePointServices.Samples
Class RetrieveSpecificItemsFields
Shared Sub Main ()
Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
Dim clientContext As New ClientContext(siteUrl)
Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")
Dim camlQuery As New CamlQuery()
Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)
clientContext.Load(collListItem, _
Function(items) items.Take(5).Include( _
Function(item) item("Title"), _
Function(item) item("Body")))
clientContext.ExecuteQuery()
Dim oListItem As ListItem
For Each oListItem In collListItem
Console.WriteLine("Title: {0} " + ControlChars.Lf + "Body: {1}" + _
ControlChars.Lf, oListItem("Title"), oListItem("Body"))
Next oListItem
End Sub
End Class
End Namespace
上面的示例将 CamlQuery 对象传递给 Load<T>(T, []) 方法,而不指定 CAML 查询字符串,这通常会返回所有列表项,但在本例中,Take<TSource>(IQueryable<TSource>, Int32) 方法限制了返回的项数。
备注
Microsoft SharePoint Foundation 2010 中 JavaScript 对象模型的 load(clientObject) 方法不支持使用以上示例中使用的 Take<TSource>(IQueryable<TSource>, Int32) 方法。
检索网站上所有列表中的项
以下示例演示如何检索网站上所有列表中前 10 项的标题。
using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointServices.Samples
{
class RetrieveFirstTenItemsAllLists
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
ListCollection collList = clientContext.Web.Lists;
clientContext.Load(
collList,
lists => lists.Where(
list => list.Hidden == false).Include(
list => list.Title,
list => list.Items.Take(10)));
clientContext.ExecuteQuery();
foreach (SP.List oList in clientContext.Web.Lists)
{
string listTitle = oList.Title;
int itemCount = oList.Items.Count;
Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount);
}
}
}
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Namespace Microsoft.SDK.SharePointServices.Samples
Class RetrieveFirstTenItemsAllLists
Shared Sub Main ()
Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
Dim clientContext As New ClientContext(siteUrl)
Dim collList As ListCollection = clientContext.Web.Lists
clientContext.Load(collList, _
Function(lists) lists.Where( _
Function(list) list.Hidden = False).Include( _
Function(list) list.Title, _
Function(list) list.Items.Take(10)))
clientContext.ExecuteQuery()
Dim oList As SP.List
For Each oList In clientContext.Web.Lists
Dim listTitle As String = oList.Title
Dim itemCount As Integer = oList.Items.Count
Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount)
Next oList
End Sub
End Class
End Namespace
备注
在 SharePoint Foundation 2010 中,JavaScript 的 load(clientObject) 方法不支持使用以上示例中使用的 Where<TSource>(IQueryable<TSource>, Expression<Func<TSource, Boolean>>) 方法。
使用列表项集合位置检索项
可以使用 ListItemCollectionPosition 类,根据项目相对于其集合的位置,来检索分页列表项。可使用 RowLimit 元素指定每页返回的项数。以下示例循环访问 Announcements 列表中的所有项,使用 CamlQuery 类的 ListItemCollectionPosition 属性和 ListItemCollection 类的 ListItemCollectionPosition 属性,按每页五项的速度,交替 get 或 set 每个集合迭代的位置。只要为每页返回了五项,循环就将继续,并使用 PagingInfo 属性显示分页信息以及所返回的五项中每个项的相关信息。如果每页返回的项数少于五个,循环将结束。
using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointServices.Samples
{
class UsingItemCollectionPosition
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
ListItemCollectionPosition itemPosition = null;
while (true)
{
CamlQuery camlQuery = new CamlQuery();
camlQuery.ListItemCollectionPosition = itemPosition;
camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='ID'/>" +
"<FieldRef Name='Title'/><FieldRef Name='Body'/>" +
"</ViewFields><RowLimit>5</RowLimit></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
itemPosition = collListItem.ListItemCollectionPosition;
foreach (ListItem oListItem in collListItem)
{
Console.WriteLine("Title: {0}: \nBody: {1}", oListItem["Title"], oListItem["Body"]);
}
if (itemPosition == null)
{
break;
}
Console.WriteLine("\n" + itemPosition.PagingInfo + "\n");
}
}
}
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client
Namespace Microsoft.SDK.SharePointServices.Samples
Class UsingItemCollectionPosition
Shared Sub Main ()
Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
Dim clientContext As New ClientContext(siteUrl)
Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")
Dim itemPosition As ListItemCollectionPosition = Nothing
While True
Dim camlQuery As New CamlQuery()
camlQuery.ListItemCollectionPosition = itemPosition
camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='ID'/>" + _
"<FieldRef Name='Title'/><FieldRef Name='Body'/>" + _
"</ViewFields><RowLimit>5</RowLimit></View>"
Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)
clientContext.Load(collListItem)
clientContext.ExecuteQuery()
itemPosition = collListItem.ListItemCollectionPosition
Dim oListItem As ListItem
For Each oListItem In collListItem
Console.WriteLine("Title: {0}: " + ControlChars.Lf + _
"Body: {1}", oListItem("Title"), oListItem("Body"))
Next oListItem
If itemPosition Is Nothing Then
Exit While
End If
Console.WriteLine((ControlChars.Lf + itemPosition.PagingInfo + ControlChars.Lf))
End While
End Sub
End Class
End Namespace
有关在 SharePoint Foundation Silverlight 对象模型上下文中检索客户端对象的信息和示例,请参阅使用 Silverlight 对象模型。