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

Concatenating C# string only when the pre check is an empty string

我是 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;
       }

我相信应该有很多聪明的方法可以做到这一点,如果有人能为我提供更好的解决方案,我们将不胜感激。

使用String.Join and String.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()));
   }

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

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