Mohanapriya R Mohanapriya R
Updated date Jul 30, 2024
In this article, we will learn how to convert dictionaries to strings in C#.
  • 2.9k
  • 0
  • 0

Converting Dictionaries to Strings in C#:

To convert a dictionary to a string in C#, we have many methods. The easy method is to iterate through the key-value pairs and concatenate them into a string using a delimiter. 

Dictionary<string, int> myDictionary = new Dictionary<string, int>()
{
    { "apple", 5 },
    { "banana", 3 },
    { "orange", 7 }
};

Now, let's convert this dictionary to a string:

string result = string.Join(", ", myDictionary.Select(kv => $"{kv.Key}: {kv.Value}"));
Console.WriteLine(result);

Output:

apple: 5, banana: 3, orange: 7

In the above code snippet, we use string.Join() to concatenate the key-value pairs into a single string. We use LINQ's Select() method to format each key-value pair as a string in the format "key: value". 

Alternative Approaches:

The other approach is to use JSON serialization. This method is especially useful if we want to serialize the dictionary for storage or communication purposes. 

using System.Text.Json;

string jsonString = JsonSerializer.Serialize(myDictionary);
Console.WriteLine(jsonString);

Output:

{"apple":5,"banana":3,"orange":7}

Comments (0)

There are no comments. Be the first to comment!!!