建立动态LINQ? [英] Build dynamic LINQ?

查看:70
本文介绍了建立动态LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LINQ查询数据.考虑一种情况,用户仅想报告3个字段中的1个? (请参见下文)

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 dynamically?

谢谢

DD

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"
        && cl.appeal_date >= Convert.ToDateTime(txtReferedFromDate.Text)
        && cl.appeal_date <= Convert.ToDateTime(txtReferedToDate.Text)
        && cs.referred_from_lho == dlLHO.Text
        && cs.adviser == dlAdviser.Text
    select new
    {
        Ref = cs.ref_no,
        ClaimType = cl.claim_type,
        ClaimStatus = cl.claim_status,
        AppealDate = cl.appeal_date
    };

gvReport.DataSource = query;

推荐答案

您可以执行以下操作:

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.

这篇关于建立动态LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆