使用 Microsoft Graph Sdk 逐页浏览集合Page through a collection using the Microsoft Graph SDKs

出于性能原因,实体的集合通常会拆分为多个页面,并且每个页面都将使用下一页的 URL 进行返回。For performance reasons, collections of entities are often split into pages and each page is returned with a URL to the next page. PageIterator类简化了分页集合的使用。The PageIterator class simplifies consuming of paged collections. PageIterator 句柄枚举当前页面并自动请求后续页面。PageIterator handles enumerating the current page and requesting subsequent pages automatically.

循环访问所有邮件Iterate over all the messages

下面的示例演示如何对用户邮箱中的所有邮件进行迭代。The following example shows iterating over all the messages in a user's mailbox.

提示

本示例将使用参数设置较小的页面大小 top 以用于演示目的。This example sets a small page size using the top parameter for demonstration purposes. 最多可以将页面大小设置为999,以最大限度地减少所需的请求数。You can set the page size up to 999 to minimize the number of requests that are necessary.

var messages = await graphClient.Me.Messages
    .Request()
    .Select(e => new {
        e.Sender,
        e.Subject
    })
    .Top(10)
    .GetAsync();

var pageIterator = PageIterator<Message>
    .CreatePageIterator(graphClient, messages, (m) => {
        Console.WriteLine(m.Subject);
        return true;
    });

await pageIterator.IterateAsync();

停止和恢复迭代Stopping and resuming the iteration

在某些情况下,需要停止迭代过程才能执行其他操作。Some scenarios require stopping the iteration process in order to perform other actions. 可以通过 false 从迭代回调中返回来暂停迭代。It is possible to pause the iteration by returning false from the iteration callback. 可以通过对 PageIterator 调用方法来恢复迭代 resumePageIteratorIteration can be resumed by calling the resume method on the PageIterator.

int count = 0;
int pauseAfter = 25;

var messages = await graphClient.Me.Messages
    .Request()
    .Select(e => new {
        e.Sender,
        e.Subject
    })
    .Top(10)
    .GetAsync();

var pageIterator = PageIterator<Message>
    .CreatePageIterator(graphClient, messages, (m) => {
        Console.WriteLine(m.Subject);
        count++;
        // If we've iterated over the limit,
        // stop the iteration by returning false
        return count < pauseAfter;
    });

await pageIterator.IterateAsync();

while (pageIterator.State != PagingState.Complete)
{
    Console.WriteLine("Iteration paused for 5 seconds...");
    Thread.Sleep(5000);
    // Reset count
    count = 0;
    await pageIterator.ResumeAsync();
}