Anda di halaman 1dari 3

Practical usage of NameValueCollection in C# Part1 In this article we are going to see the Practical usage of NameValueCollection .

Used Namespaces:
using System; using System.Collections.Specialized;

Advantage: 1. We can store duplicate key with different value or same value. 2. Using key we can get all the values of single key. 3. Single Key, but multiple values Disadvantage: 1. We can store and retirive only string values.

Step 1:

Used Namespaces:

using System; using System.Collections.Specialized;

Step 2:

Collection used to show Demo

public static NameValueCollection GetCollection() { NameValueCollection collection = new NameValueCollection(); collection.Add("Lajapathy", ":INQ"); collection.Add("partiban", "WCF"); collection.Add("partiban", "Silverlight"); collection.Add("Sathiya", "C#"); collection.Add("Sathiya", "dot net"); collection.Add("Sangita", "C#"); return collection; }

Step 3:

Used to display on the Unique keys from the collection

public void DisplayOnlyUniqueKeys() { NameValueCollection collection = GetCollection(); // No duplicates returned. foreach (string key in collection.AllKeys) { Response.Write(key + ",");

} }

Step 4:

Used to get the value of the key from the collection

public void DisplayValue() { NameValueCollection collection = GetCollection(); Response.Write(string.Format("Value :", collection["Sathiya"])); }

Step 5:

How to remove the values using the Key

public void RemoveValue() { NameValueCollection collection = GetCollection(); collection.Remove("Lajapathy"); // No duplicates returned. foreach (string key in collection.AllKeys) { Response.Write(key + ","); } }

Step 6:

How to Clear the collection using the below approach

public void ClearValue() { NameValueCollection collection = GetCollection(); collection.Clear(); // No duplicates returned. foreach (string key in collection.AllKeys) { Response.Write(key + ","); } }

Step 7:

How to get the values as Array

public void GetDataArray() { NameValueCollection collection = GetCollection(); string[] values = collection.GetValues("partiban"); // No duplicates returned. foreach (string key in values) {

Response.Write(key + ","); } }

Step 8:

How to get key using the index of collection

public void GeKey() { NameValueCollection collection = GetCollection(); string key = collection.GetKey(1); Response.Write(string.Format("Value :", key)); }

Step 9:

Declaration of Above Code snippet

protected void Page_Load(object sender, EventArgs e) { DisplayOnlyUniqueKeys(); DisplayValue(); ClearValue(); GetDataArray(); GeKey(); }

Thanks for reading this article. Have a nice day.

Anda mungkin juga menyukai