Webform中linq to sql多条件查询(小练习)

Webform中linq to sql多条件查询(小练习)

多条件查询:逐条判断,从第一个条件开始判断,如果满足,取出放入集合,再从集合中查询第二个条件。。。

Webform中linq to sql多条件查询(小练习)_第1张图片

aspx代码

复制代码
 1 
 2     
"form1" runat="server"> 3 4
5 "Label1" runat="server" Text="关键字:"> 6 "Gjz" runat="server" Font-Size="12px"> 7   8 "Label2" runat="server" Text="价格:"> 9  "price1" runat="server" Font-Size="12px" Width="52px"> 10   11 "Label3" runat="server" Text=""> 12   13 "price2" runat="server" Font-Size="12px" Width="52px"> 14   15 "select" runat="server" Text="查询" OnClick="select_Click" /> 16
17
18 "Repeater1" runat="server"> 19 20 "903" border="0" cellspacing="1" cellpadding="0" bgcolor="#6600FF"> 21"height:25px;"> 222324252627282930 31 "height:25px;"> 32333435363738394041 42 43
"260" bgcolor="#FFFFFF">名称 "160" bgcolor="#FFFFFF">上市时间 "160" bgcolor="#FFFFFF">油耗 "160" bgcolor="#FFFFFF">功率 "163" bgcolor="#FFFFFF">价格
"#FFFFFF"><%#Eval("Name") %> "#FFFFFF"><%#Eval("Time","{0:yyyy年MM月dd日}") %> "#FFFFFF"><%#Eval("Oil") %> "#FFFFFF"><%#Eval("Powers") %> "#FFFFFF"><%#Eval("Price") %>
44 45 46 47 48
49 50
复制代码

 aspx.cs代码:

 

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 public partial class test : System.Web.UI.Page
 9 {
10     protected void Page_Load(object sender, EventArgs e)
11     {
12         if(!IsPostBack)
13         {
14          coenctDataContext _conext = new coenctDataContext();
15            Repeater1.DataSource=  _conext.Car;
16            Repeater1.DataBind();
17         }
18     }
19 
20 
21     protected void select_Click(object sender, EventArgs e)
22     {
23         coenctDataContext _contest = new coenctDataContext();
24 
25         List list =  _contest.Car.ToList();
26         string key =Gjz.Text.ToString();
27         
28         //判断第一个条件是否为空,如果为空不操作,去判断第二个条件看是否满足;不为空,继续 继续查询
29         if (key != "")
30         {
31             list = list.Where(p => p.Name.Contains(key)).ToList();
32             //关键字变原色,用foreach去查看集合中满足条件的字
33             foreach(Car data in list )
34             {
35                 string s = data.Name.Replace(key, "" + key + "");
36                 data.Name = s;
37             }
38         }
39 
40         //判断第二个条件
41         string mi = price1.Text;//取text判断是否为空
42         string ma = price2.Text;//取text判断是否为空
43         
44         //先判断第二个条件中,文本框中是否为空
45         if(mi !="" && ma != "")
46         {
47             decimal min = Convert.ToDecimal(price1.Text);
48             decimal max = Convert.ToDecimal(price2.Text);
49 
50            list=    list.Where(p=>p.Price.Value>=min && p.Price<=max).ToList();
51 
52         }
53 
54         //指定数据源显示出来
55         Repeater1.DataSource = list;
56         Repeater1.DataBind();
57 
58     }
59 }
复制代码

 

你可能感兴趣的:(Webform中linq to sql多条件查询(小练习))