簡體   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