sharepoint-2013sharepoint-clientobject

SharePoint CSOM C# Load Query with Where Clause Performance


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?


Solution

  • 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.