2016-09-27 129 views
-2
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."; 
} 

https://stackoverflow.com/posts/39720620/ 或者你可以向下滾動地看到,滿足我的需要的正確答案。欣賞這一點。有沒有什麼方法可以縮短這個代碼呢?

+0

是否要添加的文本總是相同? –

+0

如果文本相同,只需創建一個單詞集合並使用Linq - 「Any」作爲例子。如果文本不同,請使用字典將關鍵字與文本相關聯,並使用循環遍歷字典。 – kiziu

+0

你也可以通過避免方法運行一個列表來檢查使用foreach/for-loop語句的項目列表。 – mahlatse

回答

-1
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(); 

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

這對我很有用~~ 謝謝〜我會添加一些東西來儘可能地壓縮它。 :D – puydan

-3

請使用以下模式:

Dictionary<string, string> wordsToCompare = new Dictionary<string, string> 
{ 
    { "Home", "Home in Home Menu is missing." }, 
    { "Users", "Even another string here" }, 
    ... 
}; 

private string GetSuffixString(string word) 
{ 
    string resultString; 
    wordsToCompare.TryGetValue(word, out resultString); 
    return resultString; 
} 

然後使用它:

StringBuilder builder = new StringBuilder(result_show.richTextBox1.Text); 
builder.Append(this.GetSuffixString(richTextBox1.Text)); 
result_show.richTextBox1.Text = builder.ToString(); 
+0

這不是一個完整的解決方案......它什麼都不做 – musefan

+0

現在應該是完整的 – Fka

+1

嗯,我不確定它達到了目標。 OP代碼建議在有多個匹配的情況下建立一個列表。它也應該使用「包含」而不是完全匹配 – musefan

-1
Dictionary<string,string> Messages = new Dictionary<string,string> {"...."}; 

var sb = new StringBuilder(); 

Messages.ForEach(p=> 
{ 
    if(p.Key.Contains(richTextBox1.Text)) 
    { 
    sb.Append(P.value); 
    } 
}); 
+1

雖然有效的答案,我會建議你包括實際的字典定義。純粹是因爲它有助於澄清你打算如何工作。在這種情況下,OP顯然不熟悉字典,所以他們不太可能知道你的意思是什麼'{「....」}' – musefan

+1

只有代碼答案不是很好的答案,試着添加幾行解釋問題是什麼,代碼如何修復它 – MikeT

2
string template = "{0} in Home Menu is missing."; 
string[] keywords = new string[] { "home", "users", "space" }; 
for (int i = 0; i < keywords.Length; i++) 
{ 
    result_show.richTextBox1.Text += richTextBox1.Text.Contains(keywords[i]) ? 
      string.Empty : string.Format(template, keywords[i]); 
} 

使用StringBuilder如果您需要某些性能

+1

您必須切換條件語句的分支:當文本不包含關鍵字時,您希望附加錯誤消息。 –

+1

@HansKesting:好點!但是現在爲時已晚,我刪除了我的upvote,我想我應該編輯答案,而不是 – musefan

+0

,可能/應該是一個foreach循環... – Vogel612

相關問題