Barry The Wizard
Barry The Wizard

Reputation: 1318

Stringify key-value pairs in 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);
    }
}

Upvotes: 101

Views: 221793

Answers (5)

Erik Anderson
Erik Anderson

Reputation: 5289

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

Upvotes: 28

Sachin Gaur
Sachin Gaur

Reputation: 13099

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".

Upvotes: 98

Leo
Leo

Reputation: 5122

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

Upvotes: 22

SAR_H
SAR_H

Reputation: 71

My goto is

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

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

Upvotes: 6

CheGueVerra
CheGueVerra

Reputation: 7963

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

Upvotes: 132

Related Questions