转换if和foreach语句以选择linq中的where

问题描述

我该如何使用 select where 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;
            }

解决方法

只需执行常规的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()会产生空值?

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...