15

What is the proper syntax for including fields dynamically in a CSOM listitems query?

For example, this would apparently work:

foreach (string field in fields)
{
  clientContext.Load(items, includes => includes.Include(i => i[field]));
}

but what would be the correct / best syntax?

As a comparison - if we know the fields beforehand we could write:

ListItemCollection items = list.GetItems(query);
clientContext.Load(items, includes => includes.Include(
   i => i["Field1"], 
   i => i["Field2"]));
22

For demonstration purposes, let's assume we have a custom list named Phones with the following fields:

  • Title (manufacturer)
  • Model

According to Fiddler, the query:

var fieldNames = new[] { "Title", "Model" };
 foreach (var fieldName in fieldNames)
 {
                    context.Load(items, includes => includes.Include(i => i[fieldName]));
 }
 context.ExecuteQuery();

and query

context.Load(items, includes => includes.Include(i => i["Title"], i => i["Model"]));
context.ExecuteQuery();

generate absolutely identical Request that is sent to SharePoint WCF Web Service /_vti_bin/client.svc/

<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="15.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
  <Actions>
    <Query Id="15" ObjectPathId="10">
      <Query SelectAllProperties="false">
        <Properties />
      </Query>
      <ChildItemQuery SelectAllProperties="false">
        <Properties>
          <Property Name="Title" ScalarProperty="true" />
          <Property Name="Model" ScalarProperty="true" />
        </Properties>
      </ChildItemQuery>
    </Query>
  </Actions>
  <ObjectPaths>
    <Method Id="10" ParentId="7" Name="GetItems">
      <Parameters>
        <Parameter TypeId="{3d248d7b-fc86-40a3-aa97-02a75d69fb8a}">
          <Property Name="DatesInUtc" Type="Boolean">true</Property>
          <Property Name="FolderServerRelativeUrl" Type="Null" />
          <Property Name="ListItemCollectionPosition" Type="Null" />
          <Property Name="ViewXml" Type="String">
            &lt;View Scope="RecursiveAll"&gt;&#xD;
            &lt;Query&gt;&#xD;
            &lt;/Query&gt;&#xD;
            &lt;/View&gt;
          </Property>
        </Parameter>
      </Parameters>
    </Method>
    <Identity Id="7" Name="740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:f0a52fd4-bd00-4bdb-a831-38df487f7f02:web:234535de-cbdf-4b3a-9f70-5fb97c73f92f:list:60633b9c-4acf-442e-b18b-ef413046b8e3" />
  </ObjectPaths>
</Request>

Summary: from the perspective of performance, for the specified cases, it does not matter how to specify fields that should be retrieved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.