linq - 将 if 和 foreach 语句转换为 linq 中的 select 和 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()
产生空值?
推荐阅读
- python - 为什么当我尝试使用 virtualenv 时它不起作用?
- google-maps - Polygon 上的 GoogleMap dragend 事件会破坏 Material Angular Snackbar
- java - JXMapViewer (openstreetmap) Drow Directions between 2 point
- javascript - Postman GET url 请求测试,用于简单的服务器 API
- checkbox - 为什么 JQuery Mobile 无法选中该复选框?
- javascript - Jquery ui 菜单问题
- python - 无法访问 jinja 模板中的 ansible 字典项
- c# - TelegramBot 不能作为 Windows 服务运行
- android - 类似软键盘的布局行为
- java - 背景上的 BLE 广告