Flame_Phoenix
Flame_Phoenix

Reputation: 17564

ToString in Dictionary c#

I have a Dictionary<int, string> in c# and I need a way to create a string with its content with the format "key1-value1, key2-value2", etc.

I am new to c#, so I created the following function that achieves this objective:

private string buildString(Dictionary<int, string> info)
{
    string result = "";
    int i = 1;
    foreach (KeyValuePair<int, string> pair in info)
    {
        if (i < info.Count)
        {
            result += pair.Key + "-" + pair.Value + ",";
        }
        else
        {
            result += pair.Key + "-" + pair.Value;
        }
        i++;
    }

    return result;
}

However, this function is inneficient and verbose. I know that C# has String.format, but I am not sure if nor how to use it.

Is there a better way to achieve the same output in a more efficient and less verbose way? If so how?

Upvotes: 1

Views: 1229

Answers (2)

Veverke
Veverke

Reputation: 11348

Does this suit your needs ?

Dictionary<int, string> dic = new Dictionary<int, string>()
{
    {1, "aaaa"},
    {2, "uodhasdhsa"},
    {3, "audaygdyasgdyasdgasydgas"}
};

List<string> list = new List<string>(dic.Select(keyValuePair => keyValuePair.Key + "-" + keyValuePair.Value));
Console.WriteLine(string.Join(", ", list));

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

string.Format is to format strings, you have values and you want to concatenate them.

You can use string.Join like this:

var result = string.Join(", ", info.Select(kvp => string.Join("-", kvp.Key, kvp.Value)));

Upvotes: 13

Related Questions