C# – 打印字典

我创建了一个字典,其中包含两个值DateTime和一个字符串。 现在我想打印从字典到文本框的所有内容。 有人知道怎么做这个吗。 我使用此代码将字典打印到控制台:

private void button1_Click(object sender, EventArgs e) { Dictionary dictionary = new Dictionary(); dictionary.Add(monthCalendar1.SelectionStart, textBox1.Text); foreach (KeyValuePair kvp in dictionary) { //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value); Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } 

只是为了结束这个

 foreach (KeyValuePair kvp in dictionary) { //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value); Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } 

改变了

 foreach (KeyValuePair kvp in dictionary) { //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value); textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } 

使用LINQ更清洁的方式

 var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString()); textBox3.Text = string.Join(Environment.NewLine, lines);