日期:2014-05-20  浏览次数:20766 次

求教Linq 动态生成 dblinq或者lambda 或者构建Expressions
C# code

using (LongXingDBDataContext db = new LongXingDBDataContext())
{
               
   this.dataGridView1.DataSource = from d in db.ZKJCXX
                                   where d.ZKID.Contains(this.tbWellPointID.Text.Trim())
                                   && d.ZM.Contains(this.tbWellPointName.Text.Trim())
                                   && !d.BF
                                   //需要判断combox的值来决定是否添加一条子查询
                                   //if(this.cmbUnit.SelectedValue == "-1")
                                   //{
                                    && d.ZB.Equals(this.cmbWellType.SelectedValue)
                                    //}
                    
                                    &&d.SSDW.Equals(this.cmbUnit.SelectedValue)
                                                    select new { 站库ID = d.ZKID, 站库名 = d.ZM, 站别名称 = [/align]d.ZBMC, 所属单位 = d.SSDWMC };
                }


问题,需要根据外部条件来动态生成lambd表达式或者dblinq但是无从下手...
有高人指点用linq.expressions但是看msdn的代码太少请帮忙解决
注:不要拼接sql字符串的方法

------解决方案--------------------
C# code


using (LongXingDBDataContext db = new LongXingDBDataContext())
{
    var obj = db.ZKJCXX.Where(p=>p.ZKID.Contains(this.tbWellPointID.Text.Trim()))
                       .Where(p=>p.ZM.Contains(this.tbWellPointName.Text.Trim())
                       .Where(p=>!p.BF)
                       .Where(p=>p.SSDW.Equals(this.cmbUnit.SelectedValue));
    if(this.cmbUnit.SelectedValue == "-1")
    {
             obj = obj.Where(p=>p.ZB.Equals(this.cmbWellType.SelectedValue));
     }
      this.dataGridView1.DataSource = from d in obj
                                         select new { 站库ID = d.ZKID, 站库名 = d.ZM, 站别名称 = [/align]d.ZBMC, 所属单位 = d.SSDWMC };
     }