将字典中的键值对转换为字符串

96

我已经制作了一个包含两个值的字典:一个 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);
    }
}

2
你已经注释掉的那一行怎么样了? - Daniel A. White
1
只有赋值、调用、递增、等待和新对象表达式可以用作语句。该错误是由此引起的。 - Barry The Wizard
8
我认为你只是在注释掉的那一行缺少了一个 string.Format - petelids
5个回答

129

只是为了结束这个话题

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

95

使用 LINQ 的更简洁方式:

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

kvp 是“键值对”的缩写。


9
[kvp => $"{kvp.Key}:{kvp.Value}"] 可以翻译为“[kvp => $"{kvp.Key}:{kvp.Value}"]”,其中 $ 符号表示字符串内插。该表达式的含义是将一个键值对(kvp)格式化为字符串,其格式为“键:值”。 - r.pedrosa

27

字典可以有多种转化为字符串的方式;以下是我的解决方案:

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

19

有很多方法可以做到这一点,这里提供一些更多的方法:

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


1
你不觉得不能像打印其他东西一样打印列表/集合有点遗憾吗? - Niton
1
string.Join(Environment.NewLine, dictionary.Select(a => $"{a.Key}: {a.Value}")) 这很漂亮,谢谢。 - Jay

3

我的首选是

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

请确保在代码中引入以下包:using static System.Text.Json.JsonSerializer;


2
我还需要添加 using System.Linq 来使用 .ToList() - marsnebulasoup

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接