[c#] C# - Print dictionary

I have made a dictionary which contains two values a DateTime and a string. Now I want to print everything from the dictionary to a Textbox. Does anybody know how to do this. I have used this code to print the dictionary to the console:

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

This question is related to c# dictionary

The answer is


There's more than one way to skin this problem so 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);

More cleaner way using LINQ

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

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;