在c#中使用不同的参数多次运行相同的方法

时间:2016-07-28 23:20:06

标签: c# restful-url

我正在调用API来获取联系人列表(它们可能在100或者1000年内),并且一次只列出100个列表,它给了我这个分页选项,其中包含一个对象。列表的末尾名为' nextpage'以及下一个100的URL等等..

所以在我的c#代码中,我得到第一个100并循环遍历它们(做某事)并查找' nextpage'对象并获取URL并重新调用API等。看起来这个下一页链接依赖于我们有多少联系人。

如果我有办法循环使用相同的代码并且仍然可以使用来自' nextpage'的新网址,请告诉我。对象并运行每100个我得到的逻辑?

1 个答案:

答案 0 :(得分:0)

psuedo-code,因为我们没有具体的例子可以使用,但是......

大多数带分页的API都会有项目总数。您可以为每次迭代设置最大项目并跟踪它,或者检查null next_object,具体取决于API如何处理它。

List<ApiObject> GetObjects() {

    const int ITERATION_COUNT = 100;
    int objectsCount = GetAPICount();

    var ApiObjects = new List<ApiObject>();

    for (int i = 0; i < objectsCount; i+= ITERATION_COUNT) {

        // get the next 100
        var apiObjects = callToAPI(i, ITERATION_COUNT); // pass the current offset, request the max per call
        ApiObjects.AddRange(apiObjects);

    }   // this loop will stop after you've reached objectsCount, so you should have all

    return ApiObjects;
}

// alternatively:

List<ApiObject> GetObjects() {

    var nextObject = null;
    var ApiObjects = new List<ApiObject>();

    // get the first batch
    var apiObjects = callToAPI(null);
    ApiObjects.AddRange(apiObjects);
    nextObject = callResponse.nextObject;

    // and continue to loop until there's none left
    while (nextObject != null) {

        var apiObjects = callToAPI(null);
        ApiObjects.AddRange(apiObjects);
        nextObject = callResponse.nextObject;   
    }

    return apiObjects;  
}

无论如何,根据两种常用的Web服务方法(遗漏了大量细节,因为这不是工作代码,只是为了演示一般方法),这是基本思想。

相关问题