组合查询:
方法一:Queryable<> 延迟查询
其特点是:读到词句代码时不会立即执行,而是在进行数据绑定时执行
优点:此期间可以进行添加查询条件,以减少数据库查询内容,来减少内存占用量
//<查询>按钮 void btn_select_Click(object sender, EventArgs e) { using (CarDataContext con = new CarDataContext()) { //进行查询,将查询到的数据放入Queryable集合中 IQueryable<Car> clist = con.Car.AsQueryable(); //其特点是:读到词句代码时不会立即执行,而是在进行数据绑定时执行 //优点:此期间可以进行添加查询条件,以减少数据库查询内容,来减少内存占用量 //对每一个条件文本框进行判断,是否有限制条件 string name = txt_name.Text.Trim(); string brand = txt_brand.Text.Trim(); string price = txt_price.Text.Trim(); if (name.Length > 0) { //如果有限制条件则添加查询条件 clist = clist.Where(r => r.Name.Contains(name.Trim())); } if (brand.Length > 0) { clist = clist.Where(r => r.Brand.Contains(brand.Trim())); } if (price.Length > 0) { string s = DropDownList1.SelectedValue; if (s == "=") clist = clist.Where(r => r.Price == Convert.ToDecimal(price)); if (s == ">=") clist = clist.Where(r => r.Price >= Convert.ToDecimal(price)); if (s == "<=") clist = clist.Where(r => r.Price <= Convert.ToDecimal(price)); } //绑定数据-此时Queryable进行数据库查询并绑定数据 Repeater1.DataSource = clist; Repeater1.DataBind(); }
方法二:Intersect 交集
void Button2_Click(object sender, EventArgs e) { //先按照查询条件,将所有的数据分别查询全部出来 using(mydbDataContext con = new mydbDataContext()) { var nameList = con.car.AsQueryable(); var brandList = con.car.AsQueryable(); var priceList = con.car.AsQueryable(); string name = txt_name.Text.Trim(); string brand = txt_brand.Text.Trim(); string price = txt_price.Text.Trim(); if (name.Length > 0) { nameList = nameList.Where(r => r.name.Contains(name)); } if (brand.Length > 0) { brandList = brandList.Where(r => r.brand.Contains(brand)); } if (price.Length > 0) { string aa = DropDownList1.SelectedValue; if (aa == "=") priceList = priceList.Where(r => r.price == Convert.ToDecimal(price)); if (aa == ">=") priceList = priceList.Where(r => r.price >= Convert.ToDecimal(price)); if (aa == "<=") priceList = priceList.Where(r => r.price <= Convert.ToDecimal(price)); } //取集合的交集 var allList = nameList.Intersect(brandList).Intersect(priceList); Repeater1.DataSource = allList; Repeater1.DataBind(); } }
分页展示:
Repeater1.DataSource = clist.Skip(Count1).Take(Count2);
Repeater1.DataBind();
int AllDataCout = clist.Count();
int Count1——跳过多少条数据 int Count2——取多少条数据 AllDataCout ——查询出来的数据一共多少条