繁体   English   中英

重构复杂的linq查询

[英]refactoring complex linq query

我创建了这个linq管道,该管道返回的dto非常适合我的需求。 但是,当我尝试保持代码整洁时,我看不到别人比我容易读懂它。 有什么干净的方法可以做到吗?

    public static IEnumerable<SubscriptionOfferList> GetSubscriptionOffers(this IEnumerable<Product> products, IEnumerable<Plan> plans) =>
         products
             .GroupBy(p => p.Metadata["SubscriptionType"])
             .Select(productGroup => new SubscriptionOfferList
             {
                Name = productGroup.Key,
                Offers = productGroup.Select(p => new SubscriptionOffer
                {
                    Id = p.Id,
                    Name = p.Name,
                    Price = p.Metadata["SubscriptionPrice"],
                    Plans = plans
                    .Where(plan => plan.ProductId == p.Id)
                    .Select(plan => new PaymentPlan
                    {
                        Name = plan.Nickname,
                        Id = plan.Id,
                        Price = plan.Tiers ?? new List<PlanTier>
                        {
                            new PlanTier
                            {
                                UnitAmount = plan.Amount.GetValueOrDefault(),
                                UpTo = null
                            }
                        },
                    }).ToList()
                }).ToList(),
             });

我不知道为什么注释不好,只是将其分解为较小的功能

private static List<Plan> MakePlans(IEnumerable<Plan> plans, int pid)
{
    return plans
            .Where(plan => plan.ProductId == pid)
            .Select(plan => new PaymentPlan
            {
                Name = plan.Nickname,
                Id = plan.Id,
                Price = plan.Tiers ?? new List<PlanTier>
                {
                    new PlanTier
                    {
                        UnitAmount = plan.Amount.GetValueOrDefault(),
                        UpTo = null
                    }
                },
            }).ToList();
}

public static IEnumerable<SubscriptionOfferList> GetSubscriptionOffers(this IEnumerable<Product> products, IEnumerable<Plan> plans) =>
     products
         .GroupBy(p => p.Metadata["SubscriptionType"])
         .Select(productGroup => new SubscriptionOfferList
         {
            Name = productGroup.Key,
            Offers = productGroup.Select(p => new SubscriptionOffer
            {
                Id = p.Id,
                Name = p.Name,
                Price = p.Metadata["SubscriptionPrice"],
                Plans = MakePlans(plans, p.Id)
            }).ToList(),
         });

在该方法的顶部加上注释,并在整个linq部分中添加一些注释,以确保它们工作正常,只要查询工作正常即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM