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

如果条件多不是两个,if-else会更复杂,那么如何简化上面的代码。

4

1 回答 1

3

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

我将返回 out Count 作为练习。

于 2013-11-04T05:57:00.397 回答