Question

i am newbie in c#,

i want to build query string , i do some conditions , every condition add another condition to where clause

i want something like that :

    // BUILD SELECT QUERY
     string where = "";
     string[] where_arr = new string[];
     if (condition1)
     {
           where_arr[index++] = " field = 5 ";
     }
      if (condition2)
     {
           where_arr[index++] = " field2 = 7 ";
     }

     if (where_arr.Count>0)
        where = " where" +  String.Join(" and ", where_arr);
     string sql = "select count(*) as count from mytable " + where;

but i do not know exactly how to declare all the variables like where_arr

Was it helpful?

Solution

// BUILD SELECT QUERY
string where = "";
List<string> where_arr = new List<string>();

if (condition1)
{
    where_arr.Add(" field = 5 ");
}

if (condition2)
{
    where_arr.Add(" field2 = 7 ");
}

if (where_arr.Count > 0)
    where = " where" + String.Join(" and ", where_arr.ToArray());
string sql = "select count(*) as count from mytable " + where;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top