Last active
July 23, 2021 11:39
-
-
Save DavidMoore/a514f7bfd9fa0d0bcec083df9fb2e538 to your computer and use it in GitHub Desktop.
Extension methods for converting NameValueCollection to a query string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Collections.Specialized; | |
using System.Linq; | |
namespace System.Collections.Specialized | |
{ | |
public static class NameValueCollectionExtensions | |
{ | |
/// <summary> | |
/// Converts a name/value collection to a query string by joining | |
/// each name and value pair with equals (=), and then combining | |
/// all the pairs into a single query string by joining them | |
/// with the ampersand (&) character. | |
/// </summary> | |
/// <param name="collection">The collection of values for the query string.</param> | |
/// <returns></returns> | |
public static string ToQueryString(this NameValueCollection collection) | |
{ | |
var results = new Dictionary<string, string>(); | |
foreach (var key in collection.AllKeys.OrderBy(s => s)) | |
{ | |
results[key] = collection[key]; | |
} | |
return string.Join("&", results.Select(pair => pair.Key + "=" + (pair.Value ?? "(null)"))); | |
} | |
/// <summary> | |
/// Converts a name/value collection to a query string by joining | |
/// each name and value pair with equals (=), and then combining | |
/// all the pairs into a single query string by joining them | |
/// with the ampersand (&) character. | |
/// </summary> | |
/// <param name="collection">The collection of values for the query string.</param> | |
/// <returns></returns> | |
public static string ToQueryString(this IEnumerable<KeyValuePair<string,string>> collection) | |
{ | |
return string.Join("&", // Combines all parameters using the ampersand separator | |
collection.OrderBy(pair => int.Parse(pair.Key.Substring("parm".Length))) // Sort all the parameters by name | |
.Select(pair => pair.Key + "=" | |
// null values should be serialized as "(null)" instead of be empty. | |
+ (pair.Value ?? "(null)"))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment