Conditional Multiple Fields Search and Filter in LINQ

Assuming we have the following table:

Person:
  PersonID,
  Name,
  Age,
  Gender

And we provide a search function that allows users to search a table according to name and / or age.

The hard part of writing an SQL query (or LINQ) is that users can choose to search for either a field or any field or field. If he wants to find everything, then he just needs to leave the text field empty.

The logic for this can be written as follows:

var p;
if(Name_TextBox=='')
{
   p=from row in person
        select row ;
}
else 
{
  p= from row in person
      where row.Name=Name_TextBox
        select row ;
}
// repeat the same for age

Now after a while the code becomes very long and messy ... How to compress the above into a single request using no if-else ?

+5
source share
3 answers

, SQL, Linq, -

var p = from p in Person
       where p.Name == Name_TextBox || Name_TextBox == String.Empty
       select p;

( , linq SQL, . var, , )

+4

       string personName = txtPersonName.Text;
       int personAge = Convert.ToInt32(txtAge.Text);
       var opportunites =  from p in this.DataContext.Persons
                            select new
                            {
                                p.PersonID,
                                p.Name,
                                p.Age,
                                p.Gender
                            };

        if (personsID != 0)
            opportunites = opportunites.Where(p => p.PersonID == personID);

        if (personName != string.Empty)
            opportunites = opportunites.Where(p => p.Name.StartsWith(personName));

        if (personAge != 0)
            opportunites = opportunites.Where(p => p.Age == personAge);

. personName , , , .

+9

why not use the null coalescing operator? eg.

var products = from a in context.products where a.ID == (productID ?? a.ID) select a;

This works really well on my system.

+2
source

All Articles