我创建了一个字典,其中包含两个值DateTime和一个字符串.现在我想打印从字典到文本框的所有内容.有人知道怎么做这个吗.我已经使用此代码将字典打印到控制台:
private void button1_Click(object sender, EventArgs e)
{
Dictionary<DateTime, string> dictionary = new Dictionary<DateTime, string>();
dictionary.Add(monthCalendar1.SelectionStart, textBox1.Text);
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
Che*_*rra 70
只是为了结束这个
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)
对此的改变
foreach (KeyValuePair<DateTime, string> 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);
}
Run Code Online (Sandbox Code Playgroud)
Sac*_*aur 50
使用LINQ更清洁的方式
var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);
Run Code Online (Sandbox Code Playgroud)
Eri*_*son 20
解决这个问题的方法不止一种,所以这是我的解决方案:
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
Run Code Online (Sandbox Code Playgroud)
有很多方法可以做到这一点,这里还有一些:
string.Join(Environment.NewLine, dictionary.Select(a => $"{a.Key}: {a.Value}"))
Run Code Online (Sandbox Code Playgroud)
dictionary.Select(a => $"{a.Key}: {a.Value}{Environment.NewLine}")).Aggregate((a,b)=>a+b)
Run Code Online (Sandbox Code Playgroud)
new String(dictionary.SelectMany(a => $"{a.Key}: {a.Value} {Environment.NewLine}").ToArray())
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用其中之一并将其封装在扩展方法中:
public static class DictionaryExtensions
{
public static string ToReadable<T,V>(this Dictionary<T, V> d){
return string.Join(Environment.NewLine, d.Select(a => $"{a.Key}: {a.Value}"));
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它像这样:yourDictionary.ToReadable()
。