c#帮助构建要查询的where子句

时间:2010-11-23 20:14:30

标签: string join c#-4.0 dynamic-arrays

我是c#的新手,

我想构建查询字符串,我做一些条件,每个条件都向where子句添加另一个条件

我想要这样的东西:

    // 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;

但我不确切知道如何声明所有变量,例如where_arr

1 个答案:

答案 0 :(得分:1)

// 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;