A union of curiosity and data science

Knowledgebase and brain dump of a database engineer

C# Dictionary from Key Value Pair String (URL)

I was searching for an elegant way to break a url into key value pairs and add them to a dictionary. 

Most of the code I came across appeared to be overkill so I wrote the function (getKeyValuePairs) below.

I return the dictionary from a function/method call because there seems to be some confusion in a few places on the web about being able to achieve this.

    class Program
        static void Main(string[] args)
            string message = "EventType=Information&EventDateGMT=2016-05-19 12:00:00&Source=Calling and Source Apps&Severity=99&Message=Hello World.!.";
            Dictionary<string, string> dict = getKeyValuePairs(message, '&', '=');
            foreach (var i in dict)  Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);

            Console.WriteLine("hit any key when ready."); Console.ReadKey();

        private static Dictionary<string, string> getKeyValuePairs(string data, char setDelimiter, char keyValueDelimiter)
            return data.Split(setDelimiter).ToDictionary(x => x.Split(keyValueDelimiter)[0], x => x.Split(keyValueDelimiter)[1]);


Add comment