Tuesday, March 13, 2012

The LINQ "where" clause

Hi guys,

I'm trying to write a LINQ query in which the where clause can accept 6 parameters. The problem is that all of them are optional parameters and need to be validated as not Null or Empty in order to be used. Normally when I used the SqlCommand I would build a string for the query via conditional statements, like:

if (!String.IsNullOrEmpty(TextBox1.Text)) { SqlString +="..." }

How do I do the equivalent to that in LINQ?

Thanks in advance!

not sure if i understand what you mean. do you mean validate a statement as a parameter? In that case you can write like this with the ? syntax:

object o;

o = (cond1 = cond2 ? truevalue : falsevalue);

MyFunction( String.IsNullOrEmpty(TextBox1.Text) ? truevalue : falsevalue)


Well, this is how I did it the non-LINQ way:

string SqlString =string.Empty;if (!String.IsNullOrEmpty(TextBox1.Text)) { SqlString +="...";}if (!String.IsNullOrEmpty(TextBox2.Text)) { SqlString +="...";}SqlCommand MyCommand =new SqlCommand(SqlString, MyConnection);

In the code above I created the SqlString variable. After that I would check if the Text property is Null or Empty for the TextBox1 & TextBox2 andonly append to the SqlString if they are not. Then I run the newly built Sql query. I need to do the equivalent in LINQ and I just don't know how.

0 comments:

Post a Comment