NameValueCollection in c#


 NamevalueCollection allows many values for one key. Needs to include System.Collections.Specialized namespace for getting this collection in your program. Performance wise it is not good while comparing with other collections. We can store duplicate keys either with different values or the same value. Using a single key we can get all the values from the collection.

/// <summary>
        /// Method is used for returning the collection
        /// </summary>
        /// <returns></returns>
        static NameValueCollection GetCollection()
        {
            //init collection
            NameValueCollection sportsCollection = new NameValueCollection();
           
            sportsCollection.Add("Cricket", "Sachin");
            sportsCollection.Add("Football", "Ronaldo");
            sportsCollection.Add("Cricket", "Tendulkar");
            sportsCollection.Add("Chess", "Anand");
            return sportsCollection;
        }
        /// <summary>
        /// main
        /// </summary>
        static void Main()
        {
            NameValueCollection collection = GetCollection();
            ///looping the keys.
            foreach (string key in collection.AllKeys) // <-- No duplicates returned.
            {
                Console.WriteLine(key);
                Console.WriteLine(collection.Get(key));
            }
            Console.ReadLine();
        }

 Output:
Cricket
Sachin,Tendulkar
Footbal
Ronaldo
Chess
Anand

No comments:

Post a Comment