如何在消息框中写入字典的内容?

时间:2013-07-15 10:44:47

标签: c# dictionary messagebox

我正在使用Visual Studio C#,我有一个带有一些记录的“string-string”Dictionary变量,例如:

{Apartment1},{Free}

{Apartment2},{Taken}

等...

如何在消息框中写入此内容,以便显示如下内容:

Apartment1 - Free

Apartment2 - Taken

等...

重要的是每条记录都在消息框中的新行内。

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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());

答案 2 :(得分:0)

var sb = new StringBuilder();

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

MessageBox.Show(sb.ToString());

答案 3 :(得分: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);

或:( using System.Linq;

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

答案 4 :(得分: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);