Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list item field values from a SP List using Client Object Model

What is the optimal way to get a list items and their properties from a SP list using Client object model?

Here is the code I'm using.

        string server = "http://localhost";
        ClientContext context = new ClientContext(server);
        Web web = context.Web;
        var spList = web.Lists.GetByTitle("Contact");
        CamlQuery query = new CamlQuery();
        var items = spList.GetItems(query);
        context.Load(items, 
            itema => itema.Include(
                item => item,
                item => item["CustomerId"]));
        context.ExecuteQuery();

        Console.WriteLine("Items");
        foreach (var item in items.ToList())
        {                              
               context.Load(item);
        }

        context.ExecuteQuery();
        foreach (var item in items)
        {
             foreach (var a in item.FieldValues)
             {
                 Console.WriteLine(a.Key + ":" + a.Value.ToString());
             }
         }

I want to remove the single liner foreach used to load list item in the context and if possible load the item field values in the first Execute Query itself.

I tried using the following

 context.Load(items, 
            itema => itema.Include(
                item => item,
                item=> item.FieldValues,
                item => item["CustomerId"]));

which doesn't work.

Any one can provide a cleaner solution?

like image 366
Sandeep Singh Rawat Avatar asked Dec 16 '10 13:12

Sandeep Singh Rawat


1 Answers

The most efficient way to query SharePoint is to use a CAML Query. By calling (SP)List.GetItems(camlQuery). You will receive always an instance of (SP)ListItemCollection.

So the the most efficient query will look like this

string server = "http://localhost";
var ctx = new ClientContext(server);
var web = ctx.Web;
var list = web.Lists.GetByTitle("Contacts");
var listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());

// always use QueryTrimming to minimize size of 
// data that has to be transfered

ctx.Load(listItemCollection,
           eachItem => eachItem.Include(
            item => item,
            item => item["CustomerId"]));
// ExecuteQuery will pull all data from SharePoint
// which has been staged to Load()
ctx.ExecuteQuery();

foreach(ListItem listItem in listItemCollection)
{
   Console.WriteLine(listItem["CustomerId"]);
}

Thorsten

like image 111
Thorsten Hans Avatar answered Oct 05 '22 19:10

Thorsten Hans