Build dynamic LINQ?

前端 未结 4 1413
我寻月下人不归
我寻月下人不归 2020-12-21 00:45

I\'m using LINQ to query data. Consider a case where the user only wants to report on say 1 of the 3 fields? (see below)

Can anyone tell me how to build the query d

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-21 01:39

    You could do something like this:

    var query = from cl in db.tblClaims
                            join cs in db.tblCases
                                on cl.ref_no equals cs.ref_no
                            where cl.claim_status == "Appeal"
                            select new
                            {
                                Ref = cs.ref_no,
                                ClaimType = cl.claim_type,
                                ClaimStatus = cl.claim_status,
                                AppealDate = cl.appeal_date,
                                cs.referred_from_lho,
                                cs.adviser
                            };
    
    if(!string.IsNullOrEmpty(txtReferedFromDate.Text) 
       && !string.IsNullOrEmpty(txtReferedToDate.Text))
      query = query.Where(cl => 
                       cl.appeal_date >= Convert.ToDateTime(txtReferedFromDate.Text) 
                    && cl.appeal_date <= Convert.ToDateTime(txtReferedToDate.Text));
    
    if(!string.IsNullOrEmpty(dlLHO.Text))
      query = query.Where(cl => cl.referred_from_lho == dlLHO.Text);
    
    if(!string.IsNullOrEmpty(dlAdviser.Text))
      query = query.Where(cl => cl.adviser == dlAdviser.Text);
    
    gvReport.DataSource = 
          query.Select(o => new { o.Ref, o.ClaimType, o.ClaimStatus, o.AppealDate });
    

    This would only use those fields as filters if they had values to filter on, otherwise they wouldn't be used in the query.

提交回复
热议问题