如何在消息框中编写词典内容
本文关键字:消息 | 更新日期: 2023-09-27 18:22:17
我在Visual Studio C#中工作,我有一个"字符串"Dictionary变量,其中包含一些记录,例如:
{Apartment1},{Free}
{Apartment2},{Taken}
等等。。。
我如何在消息框中写下这篇文章,使其显示以下内容:
Apartment1 - Free
Apartment2 - Taken
等等。。。
重要的是,每条记录都位于消息框中的新行内。
您可以循环遍历字典中的每个项并构建一个字符串,如下所示:
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))));