评估复杂的lambda表达式

时间:2016-04-12 12:04:36

标签: c# lambda

我有一个lambda表达式,我希望通过组合内部的两个函数调用来缩短它。如果您在下面的代码中看到我正在调用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
        })
};

2 个答案:

答案 0 :(得分:4)

您始终可以使用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
            };
        })
};

答案 1 :(得分:1)

这样的东西?

 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
           }
       })
 };