转换if和foreach语句以选择linq中的where
发布时间:2023-02-18 09:01:49 所属栏目:asp.Net 来源:互联网
导读:如何解决转换if和foreach语句以选择linq中的where? 我该如何使用 select 和 where 将 if语句和 foreach 更改为linq中更简洁的内容。 我试图将if语句放入 where 子句,然后使用 select 查询代替 Foreach 循环但这似乎存在类型问题,无法正常工作。 { StripeC
如何解决转换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中没有任何内容,这将为您提供一个空列表,这正是您想要的。 如果payments是null,您将得到一个例外,我认为如果真的考虑得很重,那可能也是您在这种情况下真正想要的。为什么.ListAsync()会产生空值? (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- asp.net – 测试Oracle存储过程的最简单的方法
- asp.net 根据汉字的拼音首字母搜索数据库(附 LIN
- asp.net-mvc-3 – 方法“OrderBy”必须在方法“跳
- asp.net-mvc – 在MVC4中绑定的正确方法
- asp.net-mvc – ASP.Net MVC中的自我AJAX更新部分
- asp.net – Dropzone没有绑定到模型
- 在asp.net App_Code目录中使用Nemerle
- 增加ASP.NET站点的executionTimeout和maxRequest
- 只需发布已修改的控制器,模型和ASP.NET MVC项目的
- asp.net – visual studio 2017调试无法启动程序
热点阅读