Just append two lines at back.
string Query="SELECT * FROM Table1 WHERE 1=1 ";
if (condition1) Query+="AND Col1=0 ";
if (condition2) Query+="AND Col2=1 ";
if (condition3) Query+="AND Col3=2 ";
Query.Replace("1=1 AND ", "");
Query.Replace(" WHERE 1=1 ", "");
E.g.
SELECT * FROM Table1 WHERE 1=1 AND Col1=0 AND Col2=1 AND Col3=2
will become to
SELECT * FROM Table1 WHERE Col1=0 AND Col2=1 AND Col3=2
While
SELECT * FROM Table1 WHERE 1=1
will become to
SELECT * FROM Table1
=====================================
Thanks for pointing out a flaw of this solution:
"This could break the query if, for any reason, one of the conditions contains the text "1=1 AND " or " WHERE 1=1 ". This could be the case if the condition contains a subquery or tries to check if some column contains this text, for example. Maybe this isn't a problem in your case but you should keep it in mind… "
In order to get rid of this issue, we need to distinguish the "main" WHERE 1=1 and those from subquery, which is easy:
Simply make the "main" WHERE special: I would append a "$" sign
string Query="SELECT * FROM Table1 WHERE$ 1=1 ";
if (condition1) Query+="AND Col1=0 ";
if (condition2) Query+="AND Col2=1 ";
if (condition3) Query+="AND Col3=2 ";
Then still append two lines:
Query.Replace("WHERE$ 1=1 AND ", "WHERE ");
Query.Replace(" WHERE$ 1=1 ", "");