首页 > 解决方案 > 将 if 和 foreach 语句转换为 linq 中的 select 和 where

问题描述

我将如何使用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;
            }

标签: linqasp.net-corestripe-payments

解决方案


做一个常规的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()产生空值?


推荐阅读