【发布时间】:2020-08-06 14:50:12
【问题描述】:
每当我有很多订购和过滤选项时,在我的存储库中我都会使用“switch”来决定,但代码非常重复。
如何使用 coditional order 删除重复的代码?
你有解决方案来优化这段代码吗?
示例代码:
IEnumerable<Products> products;
switch (orderBy)
{
case "Create":
products = _GFazContext.Products
//... many conditions like:
.Where(r => (productId == null || r.ProductId == productId))//Duplicate code
.Where(r => (groupId == null || r.GroupId == groupId))//Duplicate code
.Where(r => (statusId == null || r.StatusId == statusId)) //Duplicate code
//Condition about the order
.Where(r => (data1 == null || r.CreateDate >= data1))
.Where(r => (data2 == null || r.CreateDate <= data2))
.Include(r => r.Group) //Duplicate code
//Specific order
.OrderBy(p => p.CreateDate)
.Skip(pagination.SkipRecords)//Duplicate code
.Take(pagination.PageSize);//Duplicate code
break;
case "Update":
products = _GFazContext.Products
//... many conditions like:
.Where(r => (productId == null || r.ProductId == productId))//Duplicate code
.Where(r => (groupId == null || r.GroupId == groupId))//Duplicate code
.Where(r => (statusId == null || r.StatusId == statusId)) //Duplicate code
//conditions about the order
.Where(r => (data1 == null || r.LastUpdate >= data1))
.Where(r => (data2 == null || r.LastUpdate <= data2))
.Include(r => r.Group) //Duplicate code
//Specific orders
.OrderBy(p => p.LastUpdate)
.Skip(pagination.SkipRecords)//Duplicate code
.Take(pagination.PageSize);//Duplicate code
break; break;
default:
products = _GFazContext.Products
//... many conditions like:
.Where(r => (productId == null || r.ProductId == productId))//Duplicate code
.Where(r => (groupId == null || r.GroupId == groupId))//Duplicate code
.Where(r => (statusId == null || r.StatusId == statusId)) //Duplicate code
//Condition about the order
.Where(r => (data1 == null || r.ReleaseDate >= data1))
.Where(r => (data2 == null || r.ReleaseDate <= data2))
.Include(r => r.Group) //Duplicate code
//Specific orders
.OrderBy(p => p.ReleaseDate)
.Skip(pagination.SkipRecords)//Duplicate code
.Take(pagination.PageSize);//Duplicate code
break;
}
return products;
【问题讨论】:
标签: c# linq optimization entity-framework-core