字符串化字典中的键值对

Stringify key-value pairs in dictionary

我制作了一个包含两个值的字典:DateTimestring

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

我已使用此代码将词典打印到控制台:

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

只是为了关闭这个

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

对此的更改

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

使用 LINQ 的更简洁的方式:

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

kvp 是“键值对”的缩写。

解决这个问题的方法不止一种,所以这是我的解决方案:

  1. 使用Select()将键值对转换为字符串;
  2. 转换为字符串列表;
  3. 使用 ForEach() 写入控制台。
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);

有很多方法可以做到这一点,这里还有一些:

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())

此外,您可以使用其中之一并将其封装在扩展方法中:

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

并像这样使用它:yourDictionary.ToReadable()

我的目标是

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

确保包含包 using static System.Text.Json.JsonSerializer;