我使用了过多的if语句

时间:2018-10-15 14:18:33

标签: c# mysql object dynamic

我已经写了一些C#,但是我确信可以减少这17个if语句。我已经尝试了很多,但是到目前为止对我没有任何帮助。它是Windows窗体应用程序,供曾经想知道的人使用。

MySqlCommand cmdcount = new MySqlCommand("Select count(vak_id) from bezet", conn);
        var counter = cmdcount.ExecuteScalar();
        int count = 0;
        count = Convert.ToInt32(counter);

        while(count > 0)
        {
            MySqlCommand cmdklant = new MySqlCommand("Select klant_id from bezet where vak_id = @id", conn);
            cmdklant.Parameters.AddWithValue("@id", count);
            var spotinfo = cmdcount.ExecuteScalar();
            string infospot = Convert.ToString(spotinfo);

            if (infospot == "")
            {
                if (count == 8)
                {
                    P8.BackColor = Color.Green;
                }
                else if(count == 7)
                {
                    P7.BackColor = Color.Green;
                }
                else if (count == 6)
                {
                    P6.BackColor = Color.Green;
                }
                //etc...
            }
            else
            {
                //the same but then color.red
            }
            count--;
        }

1 个答案:

答案 0 :(得分:-1)

因此,您加载一个计数器,然后根据其他条件为每个关联的“ P”设置颜色

如何将那些“ P”东西放入数组中?

int count = ...
new [] { P1, P2, P3, P4 .. P8 }
.Take(count)
.Select((p, idx) => new { P = p, Index = idx})
.ToList()
.ForEach(pIndexPair => 
 {
      var infoSpot = LoadInfoSpot(pIndexPair.Index);
      pIndexPair.P.BackColor = string.IsNullOrEmpty(infospot) ? Color.Green : Color.Red;
 });