如何从List <task <model>&gt;获取模型列表?

时间:2018-04-06 11:03:56

标签: c# linq async-await

我有这个方法:

public async void OnNavigatedTo(NavigationParameters parameters)
{
    var result = await GetMatches();
    var toList = result.OrderByDescending(p => p.CreatedAt)
        .Select(async p => new CardDataModel()
        {
            HeadTitle = await generateHeadTitle(p) ,
            HeadLines = p.Sport + " - " + p.PlayersNeeded + " players needed    @" + p.Location,
            HeadLinesDesc = p.Comment,
            ProfileImage = "Person_7.jpg"
        }).ToList();

    CardList = toList;
}

哪个应该生成一个List但是因为我正在使用async / await我得到一个List<Task<CardDataModel>>我无法绑定到我的List属性。

如何获得所需的List?

2 个答案:

答案 0 :(得分:7)

您可以使用Task.WhenAllIEnumerable<Task<T>>转换为Task<T[]>,然后您可以等待它,然后使用ToList获取List ,像这样:

CardDataModel[] modelArray = await Task.WhenAll(toList);
CardList = modelArray.ToList();

答案 1 :(得分:0)

这是一个有用的扩展方法,可以添加到已提供的答案中。

public static class Ex {
    public static Task<T[]> WhenAll<T>(this IEnumerable<Task<T>> tasks) {
        return Task.WhenAll(tasks);
    }
}

并使用

var result = await GetMatches();
var toList = await result.OrderByDescending(p => p.CreatedAt)
    .Select(async p => new CardDataModel() {
        HeadTitle = await generateHeadTitle(p),
        HeadLines = p.Sport + " - " + p.PlayersNeeded + " players needed    @" + p.Location,
        HeadLinesDesc = p.Comment,
        ProfileImage = "Person_7.jpg"
    })
    .WhenAll();

CardList = toList.ToList();