Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to simplify if else using entity framework

how to simplify below code:

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 there are more conditions not two, the if-else will be more complicated, so how to simplify code above.

like image 794
qizweb Avatar asked Jun 09 '26 02:06

qizweb


1 Answers

Linq expressions can be chained. Avoid premature coercion into a 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);
   }

I'll leave returning the out Count as an exercise.

like image 161
Remus Rusanu Avatar answered Jun 11 '26 17:06

Remus Rusanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!