C# 复杂lambda表达式的求值
我有一个lambda表达式,我想通过组合内部的两个函数调用来缩短它。如果您在下面的代码中看到,我将调用C# 复杂lambda表达式的求值,c#,lambda,C#,Lambda,我有一个lambda表达式,我想通过组合内部的两个函数调用来缩短它。如果您在下面的代码中看到,我将调用this.adgroupRepository.GetBidRange两次。必须有一种方法将这些调用组合成一个调用,并从内部传递FloorValue和CeilingValue 有人能帮忙吗 new JsonResult { Data = result.Data.Where(x => x.Bidding != null).Select( x => new
this.adgroupRepository.GetBidRange
两次。必须有一种方法将这些调用组合成一个调用,并从内部传递FloorValue和CeilingValue
有人能帮忙吗
new JsonResult
{
Data = result.Data.Where(x => x.Bidding != null).Select(
x => new
{
x.ID,
x.Name,
BidRange = new
{
FloorValue = (x.Bidding.FloorPrice != null) ? x.Bidding.FloorPrice : this.adgroupRepository.GetBidRange(this.contextProvider.CurrentAccount.CurrencyCode, x.PricingModel, x.Bidding.Type).FloorValue,
CeilingValue = (x.Bidding.CeilingPrice != null) ? x.Bidding.CeilingPrice : this.adgroupRepository.GetBidRange(this.contextProvider.CurrentAccount.CurrencyCode, x.PricingModel, x.Bidding.Type).CeilingValue
},
DefaultBid = x.Bidding.BroadBid
})
};
像这样的
new JsonResult
{
Data = result.Data.Where(x => x.Bidding != null).Select(x =>
{
var bidRange = adgroupRepository.GetBidRange(
contextProvider.CurrentAccount.CurrencyCode,
x.PricingModel,
x.Bidding.Type);
return new
{
ID = x.ID,
Name = x.Name,
BidRange = new
{
FloorValue = x.Bidding.FloorPrice ?? bidRange.FloorValue,
CeilingValue = x.Bidding.CeilingPrice ?? bidRange .CeilingValue
},
DefaultBid = x.Bidding.BroadBid
}
})
};
始终可以使用lambda语句而不是表达式。这允许您编写代码块,创建局部变量,然后返回结果。此外,您还可以使用空合并运算符
??
代替带有null
检查的条件运算符
new JsonResult
{
Data = result.Data.Where(x => x.Bidding != null).Select(
x =>
{
var bidRange =
x.Bidding.FloorPrice == null
|| x.Bidding.CeilingPrice == null ?
this.adgroupRepository.GetBidRange(
this.contextProvider.CurrentAccount.CurrencyCode,
x.PricingModel,
x.Bidding.Type) :
null;
return new
{
x.ID,
x.Name,
BidRange = new
{
FloorValue = x.Bidding.FloorPrice ?? bidRange.FloorValue,
CeilingValue = x.Bidding.CeilingPrice ?? bidRange.CeilingValue
},
DefaultBid = x.Bidding.BroadBid
};
})
};
一个方法只能返回一个对象。如果GetBidRange()方法只返回一个数字,则无法更改代码。如果修改GetBidRange()以返回一个不同的对象,例如可以返回两个数字的KeyPairValue,则代码可以更简单。@jdweng它已经返回一个带有
FloorValue
和CeilingValue
的对象。此解决方案的一个小缺点是总是调用GetBidRange
,即使x.Bidding.FloorPrice
和x.Bidding.CeilingPrice
都不为空。谢谢大家的快速回答。有没有办法进一步优化这一点?i、 e.当非空值已经存在时不调用GetBidRange?@Shubhamsravastava当然,您可以设置一个条件,仅当其中至少一个值为空时才调用它。我已经用条件运算符更新了我的答案,但是你也可以使用传统的if
语句。你必须返回
匿名类型,才能编译它。@juharr谢谢。我用手机写了答案。。我会更新的。