SharePoint Foundation 2010 托管客户端对象模型概述(五) --使用 CAML 查询列表

以下示例演示了如何使用 CAML 查询在上例中创建的列表。该示例将输出我们的测试列表中的 Development 项。

C#
using System;
using Microsoft.SharePoint.Client;

class Program
{
    static void Main(string[] args)
    {
        ClientContext clientContext = new ClientContext("http://intranet.contoso.com");
        List list = clientContext.Web.Lists.GetByTitle("Client API Test List");
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml =
            @"<View>
                <Query>
                  <Where>
                    <Eq>
                      <FieldRef Name='Category'/>
                      <Value Type='Text'>Development</Value>
                    </Eq>
                  </Where>
                </Query>
                <RowLimit>100</RowLimit>
              </View>";
        ListItemCollection listItems = list.GetItems(camlQuery);
        clientContext.Load(
             listItems,
             items => items
                 .Include(
                     item => item["Title"],
                     item => item["Category"],
                     item => item["Estimate"]));
        clientContext.ExecuteQuery();
        foreach (ListItem listItem in listItems)
        {
            Console.WriteLine("Title: {0}", listItem["Title"]);
            Console.WriteLine("Category: {0}", listItem["Category"]);
            Console.WriteLine("Estimate: {0}", listItem["Estimate"]);
            Console.WriteLine();
        }
    }
}
该示例将生成以下输出。

Title: Develop proof-of-concept.
Category: Development
Estimate: 42

Title: Develop user interface.
Category: Development
Estimate: 18


您可能已注意到,在该示例中指定的 lambda 表达式与修整结果集一节所提供的示例中的 lambda 表达式之间的区别。必须使用 Include 扩展方法来指定要为所加载的集合中的每个项加载的属性。Lambda 表达式的 items 参数属于 ListItemCollection 类型,该类型当然不包含允许我们指定为集合中的项加载哪些属性的索引属性。应调用 Include 扩展方法,它允许我们指定要加载该子集合的哪些参数。Include 扩展方法中 lambda 表达式的参数的类型与集合项的类型相同。因此,您可以指定要为集合中的每个项加载的属性。

再次说明,完全没有必要了解 lambda 表达式的这种用法的确切语义,只需记住以下两点编码习惯即可:

如果要求客户端对象模型加载客户端对象(而不是客户端对象集合)的某些属性,则应在您直接添加到 Load 方法的 lambda 表达式中指定这些属性。

C#
clientContext.Load(site,
    s => s.Title,
    s => s.Description);
如果要求客户端对象模型加载客户端对象集合中每个项目的特定属性,应使用 Include 扩展方法,并将指定所需属性的 lambda 表达式传递给 Include 方法。

C#
clientContext.Load(
    listItems,
    items => items.Include(
        item => item["Title"],
        item => item["Category"],
        item => item["Estimate"]));
posted @ 2012-02-24 14:05  love007  阅读(433)  评论(1编辑  收藏  举报