Use linq query in search with empty field

I have a table with ten fields. I need a search query in LINQ that does this search. my field:

FirstName (string), LastName (string), FatherName (string), NotationId (int), DebtPrice (int), BranchName (string), DebtId (int), MeliCode (string)

my problem: when the user does not fill in the field, this field should not be used in query search
Thank you

Legal.View_Dossiers Collection

+4
source share
3 answers

you can use this code:

var query = from d in datacontext.sample where (TBoxFName.Text=="" || d.FirstName.Contains(TBoxFName.Text.Trim())) &&(TBoxLName.Text == "" || d.LastName.Contains(TBoxLName.Text.Trim())) &&(TBoxFatherName.Text == "" || d.FatherName.Contains(TBoxFatherName.Text.Trim())) && (TBoxPriceDebt.Text == "" || d.DebtPrice.ToString().Contains(TBoxPriceDebt.Text.Trim())) && (CBoxBranch.Text == "" || d.BranchName.Contains(CBoxBranch.Text.Trim())) &&(TBoxDebt.Text == "" || d.DebtId.Contains(TBoxDebt.Text.Trim())) &&(TBoxMeliCode.Text == "" || d.MeliCode.Contains(TBoxMeliCode.Text.Trim())) select d; 
+3
source

I think (unclear) you mean something like:

 IQueryable<YourType> query = /* some basic query; maybe db.TheTable */ if(!string.IsNullOrEmpty(firstName)) query = query.Where(row => row.FirstName == firstName); if(!string.IsNullOrEmpty(lastName)) query = query.Where(row => row.LastName == lastName); if(!string.IsNullOrEmpty(fatherName)) query = query.Where(row => row.FatherName == fatherName); // etc var matches = query.Take(50).ToList(); 

this uses the composition of the queries to issue the most appropriate base query; for example, if it is LINQ-to-SQL and firstName and fatherName , you will get something like:

 select top 50 {some columns} from [dbo].[TheTable] t where t.FirstName = @p0 and t.FatherName = @p1 

where @p0 and @p1 are parameters containing values.

+2
source

you can try to write:

 IEnumerable<YourType> query = //data taken from database var queryWhere = query .Where(x => x.FirstName == varFirstName || string.IsNullOrEmpty(x.FirstName )) .Where(x => x.LastName == varLastName || string.IsNullOrEmpty(x.LastName )) .Where(x => x.FatherName == varFatherName || string.IsNullOrEmpty(x.FatherName )) //...and so on... .ToList(); 
0
source

All Articles