我正在尝试从hackernews API 获取TopStories 到ListView。我想要无限滚动,所以我使用 ISupportIncrementalLoading 接口。下面是 LoadMoreItemsAsync 方法中的代码。
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(new Uri("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"));
var json = await response.Content.ReadAsStringAsync();
List<string> topStoriesID = JsonConvert.DeserializeObject<List<string>>(json);
ObservableCollection<RootObject> ro = new ObservableCollection<RootObject>();
do
{
var firstFewItems = (from topItemsID in topStoriesID
select topItemsID).Skip(lastItem).Take((int)count);
foreach (var element in firstFewItems)
{
var itemResponse = await httpClient.GetAsync(new Uri("https://hacker-news.firebaseio.com/v0/item/" + element + ".json?print=pretty"));
itemJson = await itemResponse.Content.ReadAsStringAsync();
ro.Add(JsonConvert.DeserializeObject<RootObject>(itemJson));
lastItem = (int)count;
count = count + count;
}
} while (lastItem != 500);
await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
foreach (var item in ro)
{
this.Add(item);
}
});
return new LoadMoreItemsResult() { Count = count };
运行代码给了我一个没有错误的空白页。该 URL 返回 500 个项目,所以我在这里所做的是首先我将 500 个项目 ID 存储在 topStoriesID 列表中。
然后我使用 Skip().Take() 方法获取前几个项目 ID,然后在此 ID 上运行 foreach 循环以获取实际故事并将它们添加到 ObservableCollection 对象 ro 中。我一直这样做,直到 lastItem 达到 500。
这段代码是正确的还是有更好的方法来实现它?