在字典中将键-值对字符串化

我做了一个字典,其中包含两个值: 一个 DateTime和一个 string

现在我想打印从字典到文本框的所有内容。 有人知道怎么做吗?

我使用这段代码将字典打印到控制台:

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);
}
}
184484 次浏览

Just to close this

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);
}

Changes to this

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);
}

Cleaner way using LINQ:

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

kvp is short for "key-value pair".

There's more than one way to stringify a dictionary; here's my solution:

  1. Use Select() to convert the key-value pair to a string;
  2. Convert to a list of strings;
  3. Write out to the console using ForEach().
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);

There are so many ways to do this, here is some more:

string.Join(Environment.NewLine, dictionary.Select(a => $"{a.Key}: {a.Value}"))
dictionary.Select(a => $"{a.Key}: {a.Value}{Environment.NewLine}")).Aggregate((a,b)=>a+b)
new String(dictionary.SelectMany(a => $"{a.Key}: {a.Value} {Environment.NewLine}").ToArray())

Additionally, you can then use one of these and encapsulate it in an extension method:

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}"));
}
}

And use it like this: yourDictionary.ToReadable().

My goto is

Console.WriteLine( Serialize(dictionary.ToList() ) );

Make sure you include the package using static System.Text.Json.JsonSerializer;