如果多个条件为真,如何创建多次运行的条件OR语句

时间:2015-10-06 09:16:10

标签: c# if-statement optimization multiple-conditions

现在我的代码有52个复选框,每个复选框都返回自己的值。

if (checkedListBox1.GetItemCheckState(0) == CheckState.Checked)
            {
                x += 1;
            }
if (checkedListBox1.GetItemCheckState(1) == CheckState.Checked)
            {
                x += 2;
            }
if (checkedListBox1.GetItemCheckState(2) == CheckState.Checked)
            {
                x += 1;
            }

我想将if做同样事情的语句分组到一个语句中,比如

if (checkedListBox1.GetItemCheckState(0) == CheckState.Checked ||
    checkedListBox1.GetItemCheckState(2) == CheckState.Checked ||
    checkedListBox1.GetItemCheckState(17) == CheckState.Checked )
            {
                x += 1;
            }

但是这样的代码只运行一次。是否有一个操作员可以在这种情况下提供帮助,或者我只需编写52个if语句。

2 个答案:

答案 0 :(得分:1)

我会创建一个int[]分数数组,每个可能的复选框都有一个条目:

var scores = new []
{
    1,
    2,
    1,
    4,
    2,
    1,
    // Etc up to 52 items
};

然后你可以循环遍历所有复选框并将所有分数加起来:

for (int i = 0; i < checkedListBox1.Items.Count; ++i)
    if (checkedListBox1.GetItemCheckState(i)) == CheckState.Checked)
        x += scores[i];

您还可以使用CheckedListBox.CheckedIndices遍历已检查的项目,如下所示:

x = checkedListBox1.CheckedIndices.Cast<int>().Sum(i=> scores[i]);

更好的方法IMO,就是编写一个特殊的Yaku类,用于保存列表中每个项目的信息。这将包括名称和分数(汉)。它还会覆盖ToString(),以便名称显示在列表中。

看起来有点像这样:

public class Yaku
{
    public string Name { get; }
    public int    Han  { get; }

    public Yaku(string name, int han)
    {
        Name = name;
        Han  = han;
    }

    public override string ToString()
    {
        return Name;
    }
}

然后你可以在这样的地方初始化选中的列表框:

public Form1()
{
    InitializeComponent();

    checkedListBox1.Items.Add(new Yaku("Little three dragons",  4));
    checkedListBox1.Items.Add(new Yaku("Terminal in each set",  3));
    checkedListBox1.Items.Add(new Yaku("Three closed triplets", 3));
}

并加上这样的分数:

private void button1_Click(object sender, EventArgs e)
{
    int score = checkedListBox1.CheckedItems.OfType<Yaku>().Sum(item => item.Han);
    MessageBox.Show(score.ToString());
}

答案 1 :(得分:-3)

将复选框的索引放在列表/数组中:

using System.Linq;

...
var checkboxIndices = { 0, 2, 17 };
x += checkboxIndices.Count(index =>
         checkedListBox1.GetItemCheckState(index) == CheckState.Checked);

编辑:叹息,我虽然很明显但是这里的内容与更多细节相同:

  class Yaku
   {
       public Yaku(List<int> indices, int han)
       {
           Indices = indices;
           HanValue = han;
       }
       public List<int> Indices;
       public int HanValue;
       public int ComputeValue(CheckedListBox checkedListBox)
       {
            return HanValue * Indices.Count(index =>
                checkedListBox.GetItemCheckState(index) == CheckState.Checked);
       }
   }

   ...
   var yakus = [
       new Yaku({0, 2, 17 }, 1),
       new Yaku({1}, 2)
       ...
   ];
   var totalYakuValue = yakus.Aggregate(yaku => yaku.ComputeValue());
相关问题