QueryStringCollection Class
Definition
Provides a collection of string values that is equivalent to a query string of an Uri. Implements the NameValueCollection
public class QueryStringCollection : NameValueCollection, ICollection, IDeserializationCallback, ISerializable, IReadOnlyCollection<KeyValuePair<string, string>>, IEnumerable<KeyValuePair<string, string>>, IEnumerable
- Inheritance
-
QueryStringCollection
- Implements
- Inherited Members
Examples
QueryStringCollection provides creation, parsing, and manipulation of URI query string parameters, extending NameValueCollection with URL decoding support. This example creates an empty collection and adds "search", "page", and "sort" parameters, parses an existing query string ("?category=books&author=tolkien") with and without URL decoding, and iterates key-value pairs. It also demonstrates cloning the collection and modifying the clone independently to verify they are separate instances. Console output shows the query string representation, decoded values, keys, clone independence, and entry counts.
using System;
using System.Linq;
using Cuemon.Net;
namespace MyApp.Net
{
public static class QueryStringCollectionExamples
{
public static void Demonstrate()
{
// Create an empty query string collection and add parameters.
var qsc = new QueryStringCollection();
qsc.Add("search", "dotnet");
qsc.Add("page", "2");
qsc.Add("sort", "name");
Console.WriteLine("Query string: {0}", qsc); // search=dotnet&page=2&sort=name
// Create from an existing URI query string.
var fromUrl = new QueryStringCollection("?category=books&author=tolkien");
Console.WriteLine("Parsed query: {0}", fromUrl); // category=books&author=tolkien
// Create with URL decoding enabled.
var encoded = new QueryStringCollection("q=hello%20world&lang=en", urlDecode: true);
Console.WriteLine("Decoded 'q': {0}", encoded["q"]); // hello world
// Iterate over key-value pairs.
Console.WriteLine("Parameters:");
foreach (var pair in fromUrl)
{
Console.WriteLine(" {0} = {1}", pair.Key, pair.Value);
// Use AllKeys from the base NameValueCollection.
Console.WriteLine("Keys: {0}", string.Join(", ", qsc.AllKeys));
// Clone a QueryStringCollection.
var clone = new QueryStringCollection(qsc);
clone["page"] = "3";
Console.WriteLine("Original page: {0}", qsc["page"]); // 2
Console.WriteLine("Cloned page: {0}", clone["page"]); // 3
// Count entries.
Console.WriteLine("Count: {0}", qsc.Count);
}}}
}
Constructors
| Name | Description |
|---|---|
| QueryStringCollection() | Initializes a new instance of the QueryStringCollection class. |
| QueryStringCollection(QueryStringCollection) | Initializes a new instance of the QueryStringCollection class. |
| QueryStringCollection(string, bool) | Initializes a new instance of the QueryStringCollection class. |
Methods
| Name | Description |
|---|---|
| GetEnumerator() | Returns an enumerator that iterates through the collection. |
| ToString() | Returns a string that represents this instance. |