StartLinqDataContext con = new StartLinqDataContext();
var q=con.FeeMain;
if (cmb_sf.Text != "")
q = q.Where(w => w.wtdw == cmb_sf.Text);
if (txt_blno.Text != "")
q = q.Where(w => w.blno == txt_blno.Text);
if (usetime.Checked)
q = q.Where(w => w.indatatime>= Convert.ToDateTime(dtp1.Value)&&w.indatatime<= Convert.ToDateTime(dtp2.Value));
if (cmb_ywlx.Text != "")
q = q.Where(w => w.receive == cmb_ywlx.Text);
而且要是多条件的话 这个也不适用吧
var q=from c in con.FeeMain
select c;
if (cmb_sf.Text != "")
{q = from h in q
where h.wtdw == cmb_sf.Text
select h;}
if (txt_blno.Text != "")
{q = from h in q
where h.blno == txt_blno.Text
select h;}
if (usetime.Checked)
{q = from h in q
where h.indatatime >= Convert.ToDateTime(dtp1.Value)&& h.indatatime<= Convert.ToDateTime(dtp2.Value));
select h;}
if (cmb_ywlx.Text != "")
{q = from h in q
where h.receive == cmb_ywlx.Text
select h;}
DataClasses3DataContext con = new DataClasses3DataContext();
var qu = from c in con.FeeMain select c;
if (textBox1.Text != "")
qu = qu.Where(c => c.wtdw == textBox1.Text);
if (textBox2.Text != "")
qu = qu.Where(c => c.vessel == textBox2.Text); dataGridView1.DataSource = qu; //第二种方法
DataClasses3DataContext con = new DataClasses3DataContext();
var searchPredicate1 = PredicateExtensions.True<FeeMain>();
if (textBox1.Text != "")
searchPredicate1 = searchPredicate1.And(c => c.wtdw == textBox1.Text);
if (textBox2.Text != "")
searchPredicate1 = searchPredicate1.And(c => c.vessel == textBox2.Text); var a = from c in con.FeeMain.Where(searchPredicate1) select c;
dataGridView1.DataSource = a;
原来在 执行 dataGridView1.DataSource = a; 这句代码的时候才会去查询数据库? 经过测试
在第一种方法,在尚未执行到条件的时候,数据库跟踪里没有产生相应的跟踪信息,所以不会出现
“先把数据全部查询出来再进行筛选这种情况”
哦了……
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;namespace TestLinqToSql
{
public static class PredicateExtensions
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}
//所以下边的where拼接有多少个,都只会在最后一步时才会去执行查询
var qu = from c in con.FeeMain select c;
if (textBox1.Text != "")
qu = qu.Where(c => c.wtdw == textBox1.Text);
if (textBox2.Text != "")
qu = qu.Where(c => c.vessel == textBox2.Text); dataGridView1.DataSource = qu;