【问题标题】:Convert if and foreach statement to select and where in linq将 if 和 foreach 语句转换为 linq 中的 select 和 where
【发布时间】:2020-08-10 21:44:01
【问题描述】:

如何使用 selectwhere 将我的 if 语句foreach 更改为 linq 中更简洁的内容>.

我尝试将 if 语句变成 where 子句,然后使用 select 查询来替代 Foreach 循环但这似乎有类型问题并且不起作用。

{
                StripeConfiguration.ApiKey = _appSettings.StripeSecretKey;

                var profile = await _userManager.FindByIdAsync(customerServiceID);
                var stripeId = profile.StripeAccountId;
                if (stripeId == null)
                    throw new ArgumentException("No associated Stripe account found.");

                List<PaymentMethodDto> result = new List<PaymentMethodDto>();

                var options = new PaymentMethodListOptions
                {
                    Customer = stripeId,
                    Type = "card",
                };

                var service = new PaymentMethodService();

                var payments = await service.ListAsync(options);

                if (payments != null && payments.Data?.Count > 0)
                {
                    payments.Data.ForEach((x) =>
                    {
                        result.Add(
                            new PaymentMethodDto
                            {
                                Brand = x.Card.Brand,
                                LastDigits = x.Card.Last4,
                                StripeToken = x.Id,
                                CustomerID = x.CustomerId
                            });
                    });
                }
                return result;
            }

【问题讨论】:

  • payments 什么时候会成为null

标签: linq asp.net-core stripe-payments


【解决方案1】:

只要做一个普通的Select

List<PaymentMethodDto> result = payments.Data.Select(x => new PaymentMethodDto
                            {
                                Brand = x.Card.Brand,
                                LastDigits = x.Card.Last4,
                                StripeToken = x.Id,
                                CustomerID = x.CustomerId
                            })
                            .ToList();

如果payments.Data 中没有任何内容,这将为您提供一个空列表,这就是您想要的。

如果paymentsnull,你会得到一个例外,我认为如果你认真考虑的话,这可能也是你在这种情况下真正想要的。为什么.ListAsync() 会产生空值?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    相关资源
    最近更新 更多