仅当预检查为空字符串时才连接C#字符串

时间:2015-05-16 12:00:15

标签: c# coding-style string-concatenation

我是C#新手,我试图在C#中连接一个字符串,在文本框中显示检查结果,然后点击一下按钮。我能够获得所需的输出,但代码似乎没有遵循SE中的DRY原则。

private void button1_Click(object sender, EventArgs e)
        {
            String result1, result2="";

            if (radioButton1.Checked )
            {
                result1 = radioButton1.Text;
            }
            else if (radioButton2.Checked)
            {
                result1 = radioButton1.Text;
            }
            else if (radioButton3.Checked)
            {
                result1 = radioButton3.Text;
            }


            if (checkBox1.Checked)
            {
                result2 = checkBox1.Text;
            }
            if (checkBox2.Checked)
            {
                if (result2 != "")
                {
                    result2 = result2 + "," + checkBox2.Text;
                }
                else
                result2 = checkBox2.Text;
            }
            if (checkBox3.Checked)
            {
                if (result2 != "")
                {
                    result2 = result2 + "," + checkBox3.Text;
                }
                else
                result2 = checkBox3.Text;
            }

            textBox1.Text="You like to shop from "+ result1    
                           +"for clothing styles like "+result2;
       }

我确信应该有很多聪明的方法来做这件事,如果有人能为我提供更好的解决方案,我们将非常感激。

2 个答案:

答案 0 :(得分:1)

如何使用String.JoinString.Format

这样的东西
private void button1_Click(object sender, EventArgs e)
    {
        String result1, result2="";

        if (radioButton1.Checked )
        {
            result1 = radioButton1.Text;
        }
        else if (radioButton2.Checked)
        {
            result1 = radioButton1.Text;
        }
        else if (radioButton3.Checked)
        {
            result1 = radioButton3.Text;
        }


        List<string> choices = new List<string>();
        if (checkBox1.Checked)
        {
            choices.Add(checkBox1.Text);
        }
        if (checkBox2.Checked)
        {
            choices.Add(checkBox2.Text);
        }
        if (checkBox3.Checked)
        {
            choices.Add(checkBox3.Text);
        }

        textBox1.Text=String.Format("You like to shop from {0} for clothing styles like {1}", result1, String.Join(",",choices.ToArray()));
   }

答案 1 :(得分:1)

这可以写成一行(如果你的复选框都包含在表单的控件集合中

result2 = string.Join(",", this.Controls.OfType<CheckBox>()
                .Where(x => x.Checked)
                .Select(c => c.Text));