Add strings to a string separated with a comma

I’m trying to add strings to a string but separted with a comma. At the end I want to remove the , and space. What is the cleanest way?

var message =  $"Error message : ";

if (Parameters != null)
{
    Parameters
        .ToList()
        .ForEach(x => message += $"{x.Key} - {x.Value}, "); // <- remove the , " at the end
}

return message;

Parameters is a Disctionary<string, string>

>Solution :

Use this with String.Join

message += string.Join(",",Parameters.ToList().Select(x => $"{x.Key} - {x.Value}"));

Leave a Reply