SharePoint CSOM C# 使用 Where 子句性能加载查询

SharePoint CSOM C# Load Query with Where Clause Performance

SharePoint CSOM 如何处理此代码块?

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
}

"allDocs" 集合是否已完全枚举,或者加载参数中的 Where 子句是否精确定位了单个文件?

此外,必须有更好的方法在 CSOM 中按文件名检索文件,而无需 "allDocs[0]" 索引集合选择。 你会怎么做?

如果使用下面的代码,应该可以精确定位单个文件:

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?

可能是 CAML 查询。

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

链接页面继续显示如何将文本编写器添加到 context.Log 属性 以查看由 Linq-to-Sharepoint 生成的 CAML。

在您的代码中,Linq 被转换为 IQueryable,它被传递到加载函数并转换为 CAML。然后 executeQuery 运行所有存储的 IQueryable 表达式并用结果填充变量,例如 allDocs。这是通常的Linq延迟执行。

如果您要使用 .Single(...) 方法而不是 .Where(...),Linq 会尝试立即执行查询并且 return 单个项目而不是加载方法需要的 IQueryable。

正如 Alex K 所说,执行查询后,您可以使用标准的 Linq 方法,例如 .Single()、.SingleOrDefault()、.First()、.FirstOrDefault() 等来获取唯一或结果中的第一项。