0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user7849697
  • 503
  • 1
  • 8
  • 19
  • 1
    Possible duplicates: [How to remove a suffix from end of string?](https://stackoverflow.com/q/5284591/8017690) – Yong Shun May 05 '22 at 10:18
  • 5
    No need to remove anything. Don't put it there in the first place. Use `String.Join`. – John May 05 '22 at 10:18
  • `ToList` is useless if `Parameters` already implements `IEnumerable<>` (is a List<>, IList<>, array, etc.). – Rubidium 37 May 05 '22 at 10:47

2 Answers2

3

Use this with String.Join

message += string.Join(",",Parameters.ToList().Select(x => $"{x.Key} - {x.Value}"));
sa-es-ir
  • 3,722
  • 2
  • 13
  • 31
0

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;