简体   繁体   English

建立复杂的If语句

[英]Building Complicated If-Statement

I have three if statements which they are apparently working on different functions. 我有三个if语句,它们显然在处理不同的功能。 I wanted to combine them into one function, thus I have to combine the if statement. 我想将它们组合成一个函数,因此必须组合if语句。 But I was stuck at how to use the || 但是我被困在如何使用|| && and () . &&()

My functions as filters, user can fill in whichever textboxes. 我的功能是过滤器,用户可以填写任何文本框。 On button click event, the code will find those that met criteria. 在按钮单击事件上,代码将查找符合条件的代码。 Three of them work well independently, but combining them is very tough. 其中三个独立运作良好,但是将它们组合起来非常困难。 Please bear with me and help me, I am just a very new programmer and no background at all. 请多多包涵,并帮助我,我只是一个非常新的程序员,根本没有背景。 I am stuck for days. 我被困了好几天。 ;( ;(

My filters snapshot: 我的过滤器快照:

筛选器

First: 第一:

if (itemAuthor.ToLower() == txtComAuthor.Text.ToString().ToLower())

Second: 第二:

if ((!DateTime.TryParseExact(txtComStartDate.Text, "dd/MM/yy", provider, DateTimeStyles.AssumeLocal, out startDate)
      || DateTime.Parse(itemDate, provider, DateTimeStyles.AssumeLocal) >= startDate) &&
      (!DateTime.TryParseExact(txtComEndDate.Text, "dd/MM/yy", provider, DateTimeStyles.AssumeLocal, out endDate)
      || DateTime.Parse(itemDate, provider, DateTimeStyles.AssumeLocal) <= endDate))

Third: 第三:

if (txtComKeyword1.Text != (String.Empty) && itemDescription.ToLower().Contains(txtComKeyword1.Text.ToLower()) ||
    txtComKeyword2.Text != (String.Empty) && itemDescription.ToLower().Contains(txtComKeyword2.Text.ToLower()) ||
    txtComKeyword3.Text != (String.Empty) && itemDescription.ToLower().Contains(txtComKeyword3.Text.ToLower()) ||
    txtComKeyword4.Text != (String.Empty) && itemDescription.ToLower().Contains(txtComKeyword4.Text.ToLower()))

Whether to use || 是否使用|| or && depends on whether you want the meaning at least one condition is true (use ||) or all conditions must be true (use &&). 或&&取决于您是否希望含义至少一个条件为真 (使用||)或所有条件都必须为真 (使用&&)。

If you need to mix both meanings, use () to cause conditions to be evaluated against each other, eg 如果需要混合使用两种含义,请使用()来使条件相互评估,例如

if ( (a && b) || (c && d))

means if both a and b are true or both c and d are true . 表示a和b均为true 还是 c和d为true

It makes for easier-to-read and maintain code if you define separate booleans for each portion of the compound logic. 如果您为复合逻辑的每个部分定义单独的布尔值,则它使代码更易于阅读和维护。 There is no performance difference. 没有性能差异。

bool condition1 = !DateTime.TryParseExact(txtComStartDate.Text, "dd/MM/yy", provider, DateTimeStyles.AssumeLocal, out startDate);
bool condition2 = DateTime.Parse(itemDate, provider, DateTimeStyles.AssumeLocal) >= startDate);
bool condition3 = !DateTime.TryParseExact(txtComEndDate.Text, "dd/MM/yy", provider, DateTimeStyles.AssumeLocal, out endDate);
bool condition4 = DateTime.Parse(itemDate, provider, DateTimeStyles.AssumeLocal) <= endDate);

if ((condition1
      || condition2 &&
      (condition3
      || condition4)

It will help you understand if you break each one of these clauses into functions and divvy up the complexity accordingly. 如果您将这些子句中的每一个分解为函数并相应地划分复杂度,它将有助于您理解。 Smaller pieces are easier to work with, and more maintainable in the long run. 较小的零件更易于使用,从长远来看更易于维护。 When you evolve as a programmer, you will eventually not use if statements for this at all, but rather leverage the power of polymorphism. 当您以程序员的身份发展时,您最终将根本不使用if语句,而是利用多态的功能。

For now, begin by piecing things apart. 现在,首先将事情分开。

public void btnAnalyze_onClick(){
    List<Item> results = new ArrayList<Item>();
    if(txtComAuthor.Text != String.Empty)
    { 
       List<Item> matched = filterByAuthor(txtComAuthor.Text);
       results.addRange(matched);
    }
    if(txtComStartDate.Text != String.Empty)
    {
       List<Item> matched = filterByStartDate(txtComStartDate.Text);
       results.addRange(matched);
    }
    // do the same for the others
    return results;
}



public List<Item> filterByAuthor(String desiredAuthorName){
      List<Item> matches = new ArrayList<Item>();
      //have your data access piece here, from DB/Excel/whatever.
      List<Item> candidates = ...
      foreach(Item candidate in candidates){
         if(candidate.ToLower() == desiredAuthorName){ 
            matches.add(candidate)
         }
       }
       return matches;
}

Experienced programmers will realize that there's a lot of duplication here and will have fits at the violations of DRY and performance. 经验丰富的程序员将意识到这里有很多重复项,并且适合于违反DRY和性能的情况。 That's ok. 没关系。 It can be refactored. 可以重构。 For a novice, this will be the easiest style to understand. 对于新手来说,这将是最容易理解的样式。

If you follow this style, it should be readily apparent where you need to do the filtering. 如果遵循这种样式,那么在需要进行过滤的地方应该很明显。 Basically, you will need to replace the if statement in the foreach loop with the condition for the text field you're thinking about. 基本上,您需要将foreach循环中的if语句替换为您正在考虑的文本字段的条件。

But you shouldn't need to add a bunch of clauses together doing this because you've broken things apart a little better. 但是您不需要一起添加一堆子句,因为这样可以更好地分解内容。 If you still find you need a few nested ifs, break it down further into even smaller functions. 如果仍然需要一些嵌套的if,请将其进一步分解为更小的函数。

When in doubt about logical grouping, put parentheses around every pair of operations. 如果对逻辑分组有疑问,请在每对操作之间加上括号。 That way you know how the pairs will be combined. 这样,您就知道如何将对组合。

if ((A && B) || (C && D)) will evaluate the (A && B) and (C && D) segments, then "or" those intermediate results together to produce the final value. if ((A && B) || (C && D))将评估(A && B)(C && D)段,则将这些中间结果“或”在一起以产生最终值。

For further reading, search for commutative, associative, and distributive properties of boolean logic. 为了进一步阅读,请搜索布尔逻辑的可交换,关联和分布属性。

As far as I can tell, you want to evaluate all 3 at the same time, but simply adding them into one big line will be hard to read or maintain. 据我所知,您想同时评估所有3个,但是将它们简单地添加到一行中将很难阅读或维护。 I'd recommend setting seperate bool values for each of your previous ifs: 我建议为之前的每个if设置单独的bool值:

bool firstIf = (itemAuthor.ToLower() == txtComAuthor.Text.ToString().ToLower());

Then comparing all 3 in one statement: 然后在一个语句中比较所有3个:

if (firstIf && secondIf && thirdif)
{
    Console.WriteLine("It works!");
}

This way, it is easier to make changes later if need be, and you can still read the code. 这样,以后需要时更容易进行更改,并且您仍然可以阅读代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM