linq to sql how to solve the problem of multi conditional query the answer using expression tree!

  • 2020-05-12 02:30:47
  • OfStack

This paper is suitable for small data volume. For large data volume, another method is needed, as shown in the next article
First of all, it is essential to search from the Internet. After roughly knowing the direction of the multi-condition combination query of linq, I started to do something. First, write a method of delegation:
 
private bool GetCondition(FeedBack fb) 
{ 
bool boolResult = true; 
int f_type = Int32.Parse(ddlFType.SelectedValue); 
int isClose = Int32.Parse(ddlIsClose.SelectedValue); 
int isTrue = Int32.Parse(ddlIsTrue.SelectedValue); 
string keyword = tbxKeyword.Text.FilterInjectStr(); 
if (f_type != 0) 
{ 
boolResult &= fb.F_Type == f_type; 
} 
if (isClose != -1) 
{ 
boolResult &= fb.IsClose == isClose; 
} 
if (isTrue != -1) 
{ 
boolResult &= fb.IsTrue == isTrue; 
} 
if (!keyword.IsNullOrEmpty()) 
{ 
boolResult &= fb.ContentInfo.IndexOf(keyword) > -1; 
} 
return boolResult; 
} 

Since I'm doing tests here, I'm going to put all the methods on the current page.
Note that the content in this method can be changed according to the actual situation. What I have done here is a list of message boards.
The way it's called, the list I have here is bound to the repeater control.
So you can do this:
 
private void ListDataBind() 
{ 
Expression<Func<FeedBack,bool>> expr = n => GetCondition(n); 
List<FeedBack> pageData = feedBacks.AllFeedBacks.Where(expr.Compile()).ToList(); 
FeedbackList.DataSource = pageData; 
FeedbackList.DataBind(); 
} 

Note that FeedBack is the object name of my linq to sql data source table.
In addition, some answers of the website search have errors, such as my Expression < Func < FeedBack,bool > > Written Expressionbool > > ",NND, despises these rubbish websites, and writers.
I hope you beginners can benefit from my article!

Related articles: