C#-如何简化是否使用实体框架
作者:互联网
如何简化以下代码:
public List<Cwzz_CashFlowItem> AllDataPage(int start, int limit, out int total, string xmbmLike, string xmmcLike)
{
List<Cwzz_CashFlowItem> ll;
if (xmbmLike != "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike != "" && xmmcLike == "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowCode.Contains(xmbmLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike == "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else
{
total = _ctx.Cwzz_CashFlowItem.Count();
ll = _ctx.Cwzz_CashFlowItem
.OrderBy(v => v.CashFlowCode)
.Skip(start).Take(limit).ToList();
}
return ll;
}
如果存在更多条件而不是两个条件,则if-else会更加复杂,因此如何简化上面的代码.
解决方法:
Linq表达式可以被链接.避免过早强制转换为List.
public IQueryable<Cwzz_CashFlowItem> AllDataPage(...) {
IQueryable<Cwzz_CashFlowItem> ll = _ctx.Cwzz_CashFlowItem;
if (xmbmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmbmLike));
}
if (xmcmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmcmLike));
}
return ll.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit);
}
我将把退货算作练习.
标签:if-statement,sql,c,entity-framework 来源: https://codeday.me/bug/20191122/2060628.html