簡單實(shí)現(xiàn)Linq多條件查詢
Linq多條件查詢究竟有多難呢?其實(shí)不然,在筆者的帶領(lǐng)下,你會(huì)發(fā)現(xiàn)Linq多條件查詢實(shí)現(xiàn)起來是很簡單的。
Linq多條件查詢(高級(jí)搜索),假如一共可以輸入5個(gè)條件,但是用戶根據(jù)需要可能只輸2個(gè)或3個(gè),也可能是4個(gè),寫查詢方法是不是也需要寫多個(gè)方法,還是只需要寫一個(gè)方法,下面此Linq多條件查詢方法就來幫你解決此問題。
- //用Linq 實(shí)現(xiàn)動(dòng)態(tài)多條件查詢
- Code
- private void ViewBinding()
- {
- Expression
bool>> expr = n => GetCondition(n); - var xQuery =
- DCDataContext.TestTables.Where
(expr.Compile()); - this.dataGridView1.DataSource = xQuery.ToList
(); - }
- private bool GetCondition(TestTable tb)
- {
- bool boolResult = true;
- if (txtUserNumber.Text.Trim() != string.Empty)
- {
- boolResult &= tb.UserNumber ==
- int.Parse(txtUserNumber.Text.Trim());
- }
- if (txtName.Text.Trim() != string.Empty)
- {
- boolResult &= tb.Name == txtName.Text.Trim();
- }
- if (txtClassName.Text.Trim() != string.Empty)
- {
- boolResult &= tb.ClassName == txtClassName.Text.Trim();
- }
- return boolResult;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- ViewBinding();
- }
LINQ,語言級(jí)集成查詢(Language INtegrated Query)
LINQ 提供了一條常規(guī)的途徑即給 .Net Framework 添加一些可以應(yīng)用于所有信息源( all sources of information )的具有多種用途( general-purpose )的語法查詢特性( query facilities ),這是比向開發(fā)語言和運(yùn)行時(shí)( runtime )添加一些關(guān)系數(shù)據(jù)( relational )特性或者類似 XML 特性( XML-specific )更好的方式。這些語法特性就叫做 .NET Language Integrated Query (LINQ) 。
無論什么語言實(shí)現(xiàn)多條件查詢都是需要一定得邏輯性的,用Linq實(shí)現(xiàn)更是不容易,但是大家看完上述Linq多條件查詢實(shí)現(xiàn)方法,一定會(huì)覺得實(shí)現(xiàn)起來很簡單。
【編輯推薦】