Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 几个嵌套的if条件_C#_If Statement - Fatal编程技术网

C# 几个嵌套的if条件

C# 几个嵌套的if条件,c#,if-statement,C#,If Statement,我必须检查五个条件(即用户是否希望使用此字段进行搜索)。有四个组合框和一个文本字段。用户可以使用任意字段或多个字段进行搜索。为了检查用户选择的字段,我构造了几个if和else if语句。但当我只在两种情况下这样做时,我意识到这将是多么乏味的任务,五种情况下有更好的方法吗 if (cmbAgent.Text=="") { if (cmbDegree.Text=="") { OleDbDataAdapter da = new OleDbDataAdapter("SE

我必须检查五个条件(即用户是否希望使用此字段进行搜索)。有四个组合框和一个文本字段。用户可以使用任意字段或多个字段进行搜索。为了检查用户选择的字段,我构造了几个if和else if语句。但当我只在两种情况下这样做时,我意识到这将是多么乏味的任务,五种情况下有更好的方法吗

if  (cmbAgent.Text=="")
{
    if (cmbDegree.Text=="")
    {
        OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM UniversityData", connection);
    }
    else
    {
       OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM UniversityData WHERE Expertise LIKE '%" + cmbDegree.Text + "%' ", connection);
    }
}
else if(cmbDegree.Text=="")
{
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM UniversityData WHERE SourceOfContact LIKE '%"+ cmbAgent.Text + "%' ", connection);
}
else
{
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM UniversityData WHERE SourceOfContact LIKE '%" + cmbAgent.Text + "%' and Expertise LIKE '%" + cmbDegree .Text + "%' ", connection);
}

这就是为什么大多数人会分别构建查询/查询字符串。例如:

var sb = new StringBuilder();
sb.Append("Select * from UniversityData where 1 = 1");
if(!string.IsNullOrEmpty(cmbDegree.Text.Trim())){
    sb.Append(" and Expertise like '%" + cmbDegree.Text + "%'")
}
//...
var querystring = sb.ToString();
OleDbDataAdapter da = new OleDbDataAdapter(querystring);

您可以首先构建键值列表:

List<Tuple<string, string>> keyValueList = new List<Tuple<string, string>>();

keyValueList.Add(new Tuple<string, string>("Expertise", cmbDegree.Text));
keyValueList.Add(new Tuple<string, string>("SourceOfContact", cmbAgent.Text));
最后:

var sqlQuery = "SELECT * FROM UniversityData WHERE " + string.Join(" AND ", conditionsArray);
在添加WHERE子句之前,如果数组为空,则需要添加检查,但我怀疑您是否需要帮助:-)


要添加更多条件,只需向keyValueList(1行)添加更多元组,以后无需更改其他代码。

我会这样做:

var query = "Select * from UniveristyData";
var wheres = new List<string>();
if (!cmbDegree.Text.IsNullOrEmpty())
    wheres.Add("Expertise like '%" + cmbDegree.Text + "%'");
if (!cmbAgent.Text.IsNullOrEmpty())
    wheres.Add("SourceOfContact like '%"+cmbAgent.Text+"%'");

if (wheres.Any())
    query += " where " + string.Join(" and ", wheres);

var da = new OleDbDataAdapter(query, connection);
var query=“从UniveryStyData中选择*”;
var wheres=新列表();
如果(!cmbdegate.Text.IsNullOrEmpty())
其中.Add(“类似“%”+cmbDegree.Text+“%”的专业知识);
如果(!cmbAgent.Text.IsNullOrEmpty())
其中.Add(“SourceOfContact,如“%”+cmbAgent.Text+“%”);
if(where.Any())
query+=“where”+string.Join(“and”,where);
var da=新的OleDbDataAdapter(查询、连接);

如果用户需要/想要输入多个值怎么办?
您可以轻松地动态构建查询

顺便说一下,您应该使用查询参数来防止SQL注入

// the "where 1=1" allows to always concatenate "and xxx"
// instead of testing if there were fulfilled conditions before
var query = "SELECT * FROM UniversityData WHERE 1 = 1";

var parameters = new Dictionary<string, string>();

if (txtDegree.Text != "")
{
   query += " AND Expertise like '%' + ? + '%' ";
   parameters.Add("degree", txtDegree.Text);
}

if(txtAgent.Text != "")
{
    query += " AND SourceOfContact like '%' + ? + '%' ";
    parameters.Add("agent", txtAgent.Text);
}

OleDbDataAdapter da = new OleDbDataAdapter(query, connection);
// add the parameters
foreach (var p in parameters) {
    da.SelectCommande.Parameters.Add(p.Key, OleDbType.VarChar, p.Value);
}

这不是对您的问题的回答,但在将此代码部署到production.Refactor之前,您可能应该去阅读并了解如何防止它。请对命令关键字使用全大写,如
SELECT
FROM
等。。它使快速理解命令变得更容易。:)似乎是个轻微的XY问题。您试图向用户提供什么功能?从用户界面的角度来看,复选框可能不是实现这一点的最有效的方法,它将简化代码,从而使您能够一起避免这个问题。@MalteR这是一个品味的问题。我所有的SQL都是用小写字母写的…最后一个答案是阻止SQL以正确的方式注入。
// the "where 1=1" allows to always concatenate "and xxx"
// instead of testing if there were fulfilled conditions before
var query = "SELECT * FROM UniversityData WHERE 1 = 1";

var parameters = new Dictionary<string, string>();

if (txtDegree.Text != "")
{
   query += " AND Expertise like '%' + ? + '%' ";
   parameters.Add("degree", txtDegree.Text);
}

if(txtAgent.Text != "")
{
    query += " AND SourceOfContact like '%' + ? + '%' ";
    parameters.Add("agent", txtAgent.Text);
}

OleDbDataAdapter da = new OleDbDataAdapter(query, connection);
// add the parameters
foreach (var p in parameters) {
    da.SelectCommande.Parameters.Add(p.Key, OleDbType.VarChar, p.Value);
}
// build the query
var results = from ud in context.UniversityData
              select ud;

if (txtDegree.Text != string.Empty) {
    results = from ud in results
              where ud.Expertise.Contains(txtDegree.Text)
              select ud;
}

if (txtAgent.Text != string.Empty) {
    results = from ud in results
              where ud.SourceOfContact.Contains(txtAgent.Text)
              select ud;
}

// use the results
myControl.DataSource = results.ToList(); // the ToList() call actually calls the query