0

In some utility libraries I have methods that have a params[] parameter. In many of these cases, these end up as key/value pairs which would be even more useful if I could convert these to a dictionary.

What would be the most efficient method to do this? Can I do this via Linq somehow?

Here is an example:

public static Uri appendParams(Uri uri, params string[] parameters)
    {
        if (uri == null)
        {
            return null;
        }

        if (parameters == null) {
            return uri;
        }

        var queryStringBuilder = new StringBuilder(uri.Query ?? "");

        //Would like to convert the params[] argument to a dictionary here
        Dictionary<String, String> paramsDictionary = null; // Not sure best way to do this...

        foreach (KeyValuePair<String, String> kvp in paramsDictionary)
        {
            queryStringBuilder.Append(kvp.Key + "=" + kvp.Value);
        }

        var uriBuilder = new UriBuilder(uri);
        uriBuilder.Query = queryStringBuilder.ToString();

        return uriBuilder.Uri;
    }
andersra
  • 1,103
  • 2
  • 13
  • 33

1 Answers1

0

If you're building a string and using it right away (and not using the dictionary for anything else), then you can skip the dictionary creation step and just build your query string from the parameter array:

for (int i = 0; i < parameters.Length - 1; i += 2)
{
    var concatChar = (i == 0) ? "?" : "&";
    queryString.AppendFormat("{0}{1}={2}", 
        concatChar, parameters[i], parameters[i + 1]);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43