如何在linq中访问等待方法的属性?

时间:2018-05-25 10:46:31

标签: c# linq async-await

我有这个问题,我无法找到获得价格(.Amount.GetValueOrDefault())的正确方法。

private IEnumerable<Product> GetSubsciptionOffers(IEnumerable<StripeProduct> productList)
{
    return productList
        .Select(async product => new Product
        {
            Name = product.Name,
            Id = product.Id,
            Image = new Uri(product.Images.First()),
            Description = product.Description,
            OfferType = OfferTypeEnum.Pro,
            Price = await _planRepo.GetPlanByIdAsync(product.Metadata.First().Value).Amount.GetValueOrDefault()
        });
}

错误是:

  

任务不包含金额

的定义

2 个答案:

答案 0 :(得分:6)

您必须为await

加上括号
Price = (await _planRepo.GetPlanByIdAsync(product.Metadata.First().Value)).Amount.GetValueOrDefault()

原因是.运算符的优先级高于await

答案 1 :(得分:2)

因此,您的方法是为每个产品打开数据库以获取其计划,然后返回一系列任务,每个任务都必须单独等待。这可能不是你想要的。

鉴于计划数量较少,最好先预先获取这些计划,然后将它们加入到产品中:

private async Task<IEnumerable<Product>> GetSubsciptionOffers(IEnumerable<StripeProduct> productList)
{
    //you might need to implement this method
    var plans = await _planRepo.GetAllPlansAsync();
    return productList
        .Join(plans, 
              p => p.Metadata.First().Value, 
              p => p.Id, 
              (product, plan) => (product, plan))
        .Select(x => new Product
        {
            Name = x.product.Name,
            Id = x.product.Id,
            Image = new Uri(x.product.Images.First()),
            Description = x.product.Description,
            OfferType = OfferTypeEnum.Pro,
            Price = x.plan.Amount.GetValueOrDefault()
        });
}

并以异步方式调用此方法:

IEnumerable<Product> prodc = await GetSubsciptionOffers(blah)