0

I'm working with a dictionary of type <string,string> like this:

    Dictionary<string, string> parameters = new Dictionary<string, string>()
    {
        {"llave1", "valor1"},
        {"llave2", "valor2"},
        {"llave3", "valor3"},
        {"llave4", "valor4"}
    }; 

I want to get a string like this:

"llave1=valor1&llave2=valor2&llave3=valor3&llave4=valor4"

to solve this problem I made this:

foreach (var element in parameters)
{
   strParameters += element.Key + "=" + element.Value;
   if (index < parameters.Count)
   {
      strParameters += "&";
      index++;
   }
}

I wanted to know any way to get the same string result but using linq or String.Join I'm trying to refactory my code

Johnatan De Leon
  • 156
  • 1
  • 10
  • 2
    Based on resulting string you are likely looking for adding query parameters to a url - https://stackoverflow.com/a/21855977/477420 – Alexei Levenkov Oct 30 '20 at 00:07
  • 3
    `string result = string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}"));` – Rufus L Oct 30 '20 at 01:37
  • what you are looking for its called "query string", here is a great implementation https://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c – Rod Ramírez Oct 30 '20 at 01:52
  • Does this answer your question? [Convert a Dictionary to string of url parameters?](https://stackoverflow.com/questions/23518966/convert-a-dictionary-to-string-of-url-parameters) – Peter Csala Oct 30 '20 at 11:44
  • @RufusL thanks for your answer! Can you tell me why did you use the $ symbol in the linq expression? I haven't I haven't never used this one and I'd like to know what is its function – Johnatan De Leon Oct 30 '20 at 17:37
  • It allows you to add expressions directly in a string by enclosing them in `{}` (like I did with `{kvp.Key}`, for example). It's documented here: [String Interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) – Rufus L Oct 30 '20 at 18:12

0 Answers0