2013-07-15 53 views
1

我在Visual Studio C#工作,我有一些記錄一個「串線」解釋變量,例如:如何在消息框中編寫字典的內容?

{Apartment1},{Free} 

{Apartment2},{Taken} 

等等

我怎麼能寫這裏面一個消息框,以便它顯示是這樣的:

Apartment1 - Free 

Apartment2 - Taken 

等等

重要的是,每一個記錄是在消息框中新行內。

+3

你嘗試過這麼遠嗎?據推測,你知道如何訪問你的字典中的每個項目?你知道如何連接字符串?什麼阻止你? –

回答

0
var sb = new StringBuilder(); 

foreach (var kvp in dictionary) 
{ 
    sb.AppendFormat("{0} - {1}\n", kvp.Key, kvp.Value); 
} 

MessageBox.Show(sb.ToString()); 
5

你可以循環儘管在字典中的每個項目,並建立一個字符串,像這樣:

Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
StringBuilder sb = new StringBuilder(); 

foreach (var item in dictionary) 
{ 
    sb.AppendFormat("{0} - {1}{2}", item.Key, item.Value, Environment.NewLine); 
} 

string result = sb.ToString().TrimEnd();//when converting to string we also want to trim the redundant new line at the very end 
MessageBox.Show(result); 
+0

謝謝,工作很棒! – Zannix

1

它可以通過一個簡單枚舉的方式來完成:

// Your dictionary 
    Dictionary<String, String> dict = new Dictionary<string, string>() { 
    {"Apartment1", "Free"}, 
    {"Apartment2", "Taken"} 
    }; 

    // Message Creating 
    StringBuilder S = new StringBuilder(); 

    foreach (var pair in dict) { 
    if (S.Length > 0) 
     S.AppendLine(); 

    S.AppendFormat("{0} - {1}", pair.Key, pair.Value); 
    } 

    // Showing the message 
    MessageBox.Show(S.ToString()); 
+0

+1不能以冗餘的新行結束......可能必須添加到我的答案;-) – musefan

0
string forBox = ""; 
foreach (var v in dictionary)    
    forBox += v.Key + " - " + v.Value + "\r\n"; 
MessageBox.Show(forBox); 

OR:

string forBox = ""; 
foreach (string key in dictionary.Keys) 
    forBox += key + " - " + dictionary[key] + "\r\n"; 
MessageBox.Show(forBox); 

OR:(using System.Linq;

MessageBox.Show(String.Join("\r\n", dictionary.Select(pair => String.Join(" - ", pair.Key, pair.Value)))); 
0

是的,你可以做到這一點與下面的代碼:

Dictionary<string, string> dict= new Dictionary<string, string>(); 
StringBuilder sb = new StringBuilder(); 

foreach (var item in dict) 
{ 
    sb.AppendFormat("{0} - {1} \\r\\n", item.Key, item.Value); 
} 

string result = sb.ToString(); 
MessageBox.Show(result); 
相關問題