【问题标题】:Handling Permutations of If Statements in C#在 C# 中处理 If 语句的排列
【发布时间】:2015-01-26 11:47:25
【问题描述】:

我有一些存储值的列表。现在我想创建 If-Statements 来处理这个问题,但这太多了。例如:

 if(list1.Count==0 && list2.Count==0)
 {
 //do something
 } 
 if(list1.Count==0 && list3.Count==0)
 {
 //do something
 }
 if(list1.Count==0 && list2.Count==0 && list3.Count==0)
 {
 //do something
 }

所以如果我有大约 10 个列表,就会有大量的 if 语句。有没有更好的方法来处理它?我没有发现任何有用的东西。 谢谢!

【问题讨论】:

  • 欢迎来到 Stack Overflow。我认为您的问题在Code Review 中会更好。请阅读FAQHow to Askhelp center 作为开始..
  • 如果不了解您需要实现的逻辑就很难回答这个问题......
  • @SonerGönül - 这不是审查。
  • 像@SonerGönül 所说的那样发布到 CodeReview 可能会对您有所帮助。如果你不能使用 switch/case,你可以做的是添加列表的计数并将它们保存在 int 中,然后检查这些值。不过,我不知道这对您是否有意义,因为我不知道您的具体示例。
  • @HenkHolterman 实际上是这样。 OP 正在寻求改进他的解决方案的方法,而不是他的代码中的错误。它工作正常,他只是不喜欢代码。这绝对是 Code Review 材料,而不是 Stack Overflow。

标签: c# if-statement permutation


【解决方案1】:

看到粘贴在这里的代码,我可以给出建议的一种方式是你有一些像这样的重复内容

               if(list1.Count==0 && list2.Count==0)

然后

              if(list1.Count==0 && list2.Count==0 && list3.Count==0)

其中一个建议是像这样按条件计算

              bool onetwo =  list1.Count==0 && list2.Count==0;
              bool thirdalone = list3.Count == 0;

现在代码可以像这样更好

               if(onetwo){
               }
               if(onetwo && thirdalone){
               }

如果您希望可以使用位掩码来生成所有这些,例如,这里 n 是我们拥有的总列表。

             bool[] statu = new bool[1 << n];        

             for(int i = 1 ; i < (1<< n) ; i++){
                  bool result = true;                  
                  for(int j = 0 ; j < 32 ; j++){
                    if(i & ( 1 << j) > 0){
                        //this position is part of set
                         if(list[j].count == 0)
                                  result = false;
                     }
                 }
                 status[i] = result;
             }

但这只是更语义化的方式,没有什么可以提高性能等。

【讨论】:

  • 好吧,这比我的要好一点,但没有办法迭代吗?仅用于相互测试 28 个 if 语句。
  • 好的,谢谢!我不需要性能增强。我只是想缩短一点,因为不写这么多代码。
  • 赞成这个,因为它比我的尝试更好:)
【解决方案2】:

如果您需要检查每个排列,您可以执行以下操作:

bool b1 = ( list1.count == 0 );
bool b2 = ( list2.count == 0 );
bool b3 = ( list3.count == 0 );
bool b4 = ( list4.count == 0 );
// etc etc

BitArray arr = new BitArray(new bool[4] { b1, b2, b3, b4 });
byte[] bits = new byte[4];
arr.CopyTo(bits, 0);
int x = BitConverter.ToInt32(bits, 0);

switch (x)
{
   case 1: // only list 1 is empty
   case 2: // only list 2 is empty
   case 3: // only list 1 and list 2 are empty
   case x: // and so on.
}

我不会说它是否更具可读性,但我宁愿保持这样的东西是未来而不是巨大的 if/else/else if 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多