0

How does SharePoint CSOM handle this block of code?

FileCollection allDocs = libFolder.Files;
clientContext.Load(allDocs, files => files.Where(file => file.Name == "test.docx");
clientContext.ExecuteQuery();

if (allDocs.Count > 0)
{
    File currentDoc = allDocs[0];
    // continue
}

Is the "allDocs" collection fully enumerated, or does the Where clause in the Load parameters pinpoint a single file?

Also, there has to be a better way of retrieving a file by filename in CSOM without the "allDocs[0]" indexed collection selection. How would you do it?

InvoiceGuy
  • 22
  • 2
  • 10

2 Answers2

4

it should pinpoint the single file if using code below:

FileCollection allDocs = libFolder.Files.Where(file => file.Name == "test.docx");
clientContext.LoadQuery(allDocs); // IQueryable
clientContext.ExecuteQuery();
// it should query on server and return only requested items without enumerating 
// whole library
// i think your code does the same, but im not sure here
// i personally prefer using syntax above
// note that im using LoadQuery, but not Load method

// you can select a single item like this without awkward allDocs[0] syntax
var singleDoc = allDocs.SingleOrDefault();
if (singleDoc != null) {
    // do something
}

How would you do it?

Probably CAML Query.

Alex K
  • 395
  • 3
  • 10
0

Microsoft® SharePoint® Server 2010 lets you use LINQ to SharePoint to take advantage of the LINQ framework and LINQ to Entities against SharePoint lists. The LINQ framework will convert LINQ to SharePoint statements into collaborative application markup language (CAML), and then execute the CAML against the SharePoint object model or Web Services. Source: MSDN

The linked page goes on to show how you can add a text writer to the context.Log property to view the CAML that is generated by Linq-to-Sharepoint.

In your code, the Linq is turned into an IQueryable which is passed into the load function and converted to CAML. The executeQuery then runs all the stored IQueryable expressions and populates variables such as allDocs with the results. This is the usual Linq delayed execution.

If you were to use the .Single(...) method instead of .Where(...), the Linq would try to execute the query immediately and return a single item instead of an IQueryable which the load method is expecting.

As Alex K said, after the query has been executed you can use the standard Linq methods such as .Single(), .SingleOrDefault(), .First(), .FirstOrDefault() etc to get the only or first item from the results.

Stephen Turner
  • 7,125
  • 4
  • 51
  • 68