user7849697
user7849697

Reputation: 597

Add strings to a string separated with a comma

I'm trying to add strings to a string but separated 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 Dictionary<string, string>.

Upvotes: 0

Views: 76

Answers (2)

sa-es-ir
sa-es-ir

Reputation: 5042

Use this with String.Join

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

Upvotes: 3

user16560377
user16560377

Reputation:

you can use join method but if you want to know idea you can see this code

var message =  $"Error message : ";
var sep = "";
if (Parameters != null)
{
    Parameters
        .ToList()
        .ForEach(x => {
            message += $"{sep} {x.Key} - {x.Value}";
            sep = ",";
         });
}

return message;

Upvotes: 0

Related Questions