puydan puydan - 2 months ago 6
C# Question

Is there any method to make if else shorter to this code?

if (richTextBox1.Text.Contains("Home") == false)
{
result_show.richTextBox1.Text += "Home in Home Menu is missing.";
}

if (richTextBox1.Text.Contains("Users") == false)
{
result_show.richTextBox1.Text += "Users in Home Menu is missing.";
}

if (richTextBox1.Text.Contains("Space") == false)
{
result_show.richTextBox1.Text += "Space in Home Menu is missing.";
}


http://stackoverflow.com/posts/39720620/
Or you can scroll down to see the answer that meet the right of my need. Appreciate for this.

Answer
var list = new List<TextAndMessage>()
{
    new TextAndMessage {TextToCompare = "Home", Message = "Home in Home Menu is missing."},
    new TextAndMessage {TextToCompare = "Users", Message = "Home in Home Menu is missing."}
};

var sb = new StringBuilder();
foreach (var item in list)
{
    if (!richTextBox1.Text.Contains(item.TextToCompare))
    {
        sb.Append(item.Message);
    }
}
//Assigning at the end, as you might falsely check that the string is contained in textbox, that has come from one of the messages.
result_show.richTextBox1.Text = sb.ToString();

and

public class TextAndMessage
{
    public string TextToCompare { get; set; }
    public string Message { get; set; }
}