Thursday, July 31, 2014

How to Serializing Dictionary Based Collection into Query String?


     Here I will show you how to serialize a dictionary object into query string. The solution is based on LINQ ,Obiviously same thing can be acheived by running CLASSICAL  FOR / FOR EACH Loop that might be more simpler but just for fun we will try to use LINQ here.
      First I will create a Test dictionary on which we will proceed to experiment.I created my dictionary object & added some test data into it as follows.

        /*create a test data*/

        Dictionary<string, string> dict = new Dictionary<string, string>();

        dict.Add("action", "set");

        dict.Add("user-id", "aaid");

        dict.Add("password", "pwd");

        dict.Add("server", "192.168.0.1");

        dict.Add("mode", "funny");

        dict.Add("deviation", "360");

        dict.Add("policyNo", "32543245");

        dict.Add("amt", "100");

        /*create a test data*/

Method 1 :

  string result = dict.Aggregate

                        (

                        "?",

                            (keyString, pair) => keyString + "&" + pair.Key + "=" + pair.Value

                         ).Replace("?&", "?");



Let’s break this code as into 2 steps

        a)     Building desired output

        string result = dict.Aggregate

                        (
                        "?",

                            (keyString, pair) => keyString + "&" + pair.Key + "=" +                    

                            pair.Value

                         );


     Here we are using inbuilt Aggregate function with first parameter as seed i.e. initial value of final aggregated string .In second parameter we are doing some lambda expression which takes key & value of each item in dictionary and does following action

 Aggregated string = Aggregated string’s value in previous iteration + keyString + "&" + pair.Key + “=" + pair.Value

        b)     Final Correction: what output we get in above part has string like ?&Key1=value1&Key2=Value2 we need to make it resemble normal query string from URL hence we will do tricky replace call over it as below.

          Replace("?&", "?")

 Output:

   ?action=set&user-id=aaid&password=pwd&server=192.168.0.1&mode=funny&deviation=360&policyNo=32543245&
     amt=100

          That’s our serialized string.

Method 2 :
        result = dict.Aggregate(
                        "?",

                        (keyString, pair) => (dict.Keys.ToList().IndexOf(pair.Key) == 0) ? keyString + pair.Key + "=" + pair.Value : keyString 
                                   + "&" + pair.Key + "=" + pair.Value

                  );

     Method second also uses Aggregate function from dictionary object yet trick is remove replace call by using ternary operator within lambda expression,
     
     Here I check index of current key if it’s 0th then I pass string without “&” sign otherwise with “&”   sign this way in first call we will avoid “?&”
   Output:
      ?action=set&user-id=aaid&password=pwd&server=192.168.0.1&mode=funny&deviation=360&policyNo=32543245&    
        amt=100

Method 3:

  result = "?" + string.Join("&", (string[])

                            (

                            from

                                m in dict

                            select

                                string.Concat(m.Key, "=", m.Value)

                            ).ToArray());

            Here I first run LINQ over dictionary object as

                            from

                                m in dict

                            select

                                string.Concat(m.Key, "=", m.Value

which will be like collection with each element like “Key_i=Value_i” then I convert this collection to string array and join each element using glue “&” functions that comes in picture in string.join normally  used for string aggregation.

  
     Output:
            ?action=set&user-id=aaid&password=pwd&server=192.168.0.1&mode=funny&deviation=360&
               policyNo=32543245amt=100

         Thanks & Happy Coding !