C# - 打印字典

Bar*_*ard 46 c# dictionary

我创建了一个字典,其中包含两个值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)

  • [使用 $ - 字符串插值](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) `kvp =&gt; $"{kvp.Key}:{kvp.Value }“` (12认同)
  • 我知道这很疯狂,但这意味着对.:) (4认同)
  • @ jtsmith1287两天是疯了吗? (4认同)
  • 关键,价值和**对**. (2认同)
  • @jtth不仅疯了而且2天了... wth (2认同)

Eri*_*son 20

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

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


Leo*_*cia 8

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

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