2013-11-04 64 views
3

如何簡化下面的代碼:如何簡化,如果其他使用實體框架

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; 
} 

如果有多個條件,而不是兩個,如果 - 否則會更復雜,所以如何簡化上面的代碼。

回答

3

Linq表達式可以鏈接。避免過早強迫進入名單<>。

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); 
    } 

我將離開返回作爲練習。