Это лучший способ объединить эти операторы linq / lambda вместе на основе условий? Чтобы мне не приходилось присоединяться к одному и тому же много раз.
Я не эксперт, но кажется, что есть некоторая избыточность? И, возможно, путь выполнения не самый эффективный!
напр.
var products = context.Products.Select(c => c);
if (input.DefendantId != null)
{
products =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
where pd.DefendantId == input.DefendantId
select p;
}
if (input.DefendantCode != null && input.DefendantId == null)
{
products =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
join d in context.Defendants
on pd.DefendantId equals d.Id
where d.DefendantCode.Any(rp => EF.Functions.Like(d.DefendantCode, "%" + input.DefendantCode + "%"))
select p;
}
if (input.ProductId != null)
{
products = products.Where(c => c.Id == input.ProductId);
}
if (input.ProductName != null && input.ProductId == null)
{
products = products.Where(c => EF.Functions.Like(c.ProductName, "%" + input.ProductName + "%"));
}
var productsVM =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
join d in context.Defendants
on pd.DefendantId equals d.Id
select new GetProductsReturnViewModel
{
Id = p.Id,
ProductName = p.ProductName,
DefendantCode = d.DefendantCode
};
switch (input.SortBy + "_" + input.OrderBy)
{
case "productName_DESC":
productsVM = productsVM.OrderByDescending(c => c.ProductName);
break;
default:
productsVM = productsVM.OrderBy(c => c.ProductName);
break;
}
if (input.PageSize != 0)
{
productsVM = productsVM.Skip((input.Page - 1) * input.PageSize).Take(input.PageSize);
}
return productsVM;