1

我在 Visual Studio C# 中工作,我有一个带有一些记录的“字符串字符串”字典变量,例如:

{Apartment1},{Free}

{Apartment2},{Taken}

ETC...

我怎样才能在消息框中写这个,以便它显示如下内容:

Apartment1 - Free

Apartment2 - Taken

ETC...

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

4

5 回答 5

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);
于 2013-07-15T10:48:53.480 回答
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());
于 2013-07-15T10:53:42.927 回答
0
var sb = new StringBuilder();

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

MessageBox.Show(sb.ToString());
于 2013-07-15T10:48:13.790 回答
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);
于 2013-07-15T10:59:34.057 回答
0
string forBox = "";
foreach (var v in dictionary)            
    forBox += v.Key + " - " + v.Value + "\r\n";
MessageBox.Show(forBox);

或者:

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))));
于 2013-07-15T10:54:43.150 回答