Extension Method to append a list of parameters to existing Uri as query In Windows Universal, none of the builder classes for web requests are available, nor can I use System.Web. 

How would you optimize (shorten, perform) the extension method below, considering the following requirements:

Sample: http://www.foo.com?bar=foo&amp;foobar=bar


Append a list of key/value parameters as uri parameter
Encode the parameters for the web
Append also if the original uri already contains any query parameters (you do not have to check whether there is a identical pair


How much do you like this implementation ?:

    public static Uri AppendParameters(this Uri uri, IDictionary&lt;string, string&gt; parameters)
    {
        var concatenatedParameters = parameters.Select(pair =&gt;
            $"{WebUtility.UrlEncode(pair.Key)}={WebUtility.UrlEncode(pair.Value)}");

        var query = string.Join("&amp;", concatenatedParameters);
        var uriString = string.IsNullOrEmpty(uri.Query) ?
            uri.OriginalString + $"?{query}" :
            uri.OriginalString + $"&amp;{query}";

        return new Uri(uriString);
    }
You should validate both your arguments for null and throw an ArgumentNullException accordingly.

if (uri == null)
{
    throw new ArgumentNullException(nameof(uri));
}


You could add an early return if the parameters collection is empty as there's no work to actually do.

I'd also use the UriBuilder class like this:

var builder = new UriBuilder(uri);
builder.Query = uri.Query != null &amp;&amp; uri.Query.Length &gt; 1 
    ? $"{uri.Query.Substring(1)}&amp;{query}"
    : builder.Query = query;

return builder.Uri;


It's basically the same, but it looks a little clearer to me. If you don't want to use the builder, you can at least fully interpolate your strings:

uri.OriginalString + $"?{query}"


Could be

$"{uri.OriginalString}?{query}"


Update


  Can you explain why uri.Query != null &amp;&amp; uri.Query.Length &gt; 1 is better than !string.IsNullOrEmpty(uri.Query)


The reason is that uri.Query may return just a question mark e.g. in this example:

new Uri("http://www.google.com?").Query
// returns "?"


If we just checked null or string.Empty then we could end up with a uri like https://www.google.com/?&amp;foo=bar. By checking if the length is greater than 1, we can be sure we won't output a URI with "?&amp;" in it. Although it is valid, it's a bit ugly.