重构复杂的linq查询



我创建了这个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部分中放一些注释,只要查询工作正常,就可以了。

最新更新