我在 Visual Studio C# 中工作,我有一个带有一些记录的“字符串字符串”字典变量,例如:
{Apartment1},{Free}
{Apartment2},{Taken}
ETC...
我怎样才能在消息框中写这个,以便它显示如下内容:
Apartment1 - Free
Apartment2 - Taken
ETC...
重要的是,每条记录都位于消息框中的新行内。
我在 Visual Studio C# 中工作,我有一个带有一些记录的“字符串字符串”字典变量,例如:
{Apartment1},{Free}
{Apartment2},{Taken}
ETC...
我怎样才能在消息框中写这个,以便它显示如下内容:
Apartment1 - Free
Apartment2 - Taken
ETC...
重要的是,每条记录都位于消息框中的新行内。
您可以遍历字典中的每个项目并构建一个字符串,如下所示:
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);
可以通过简单的枚举来完成:
// 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());
var sb = new StringBuilder();
foreach (var kvp in dictionary)
{
sb.AppendFormat("{0} - {1}\n", kvp.Key, kvp.Value);
}
MessageBox.Show(sb.ToString());
是的,您可以使用以下代码来实现:
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);
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))));