Sunday, January 11, 2015

Split string to Dictionary C#

Here is a neat little code that would split a string and puts the values in a dictionary..

For ex if the string is to=suman&From=bobby&subject=Hello How are you&Body=TEST

the following code would split the strings into a dictionary so that you can access by myStr["to"] instead of myStr[0],[1] etc..

Sometimes it will be handy to access by name instead of array ...

you might have to change the below code so that if your outer seperator isnt '&'  change it to your character.. you can also change the inner seperator from '=' to anything you want.

public static Dictionary  splitStringToaDictionary(string stringToConvertToDict)
    {
                 
            string[] splitSTR= stringToConvertToDict.Split('&');
               var  mydictionary = new Dictionary(splitSTR.Length);
                foreach (string item in splitSTR)    
                {        
                    List list = new List(item.Split('=')); 
                    mydictionary.Add(list[0], list[1]);
                                    
                }
       
        return mydictionary;
    }

//same method as above overloaded

public static Dictionary  splitStringToaDictionary(string stringToConvertToDict,char outerSeperator, char innerSeperator)
    {
                 
            string[] splitSTR= stringToConvertToDict.Split(outerSeperator);
               var  mydictionary = new Dictionary(splitSTR.Length);
                foreach (string item in splitSTR)    
                {        
                    List list = new List(item.Split(innerSeperator)); 
                   mydictionary.Add(list[0], list[1]);
                                    
                }
       
        return mydictionary;
    }

In case if your seperator isnt just one character but multiple characters like a string for ex #abc# ... i.e A#abc#Borwn#abc#Fox

then you need to use
item.Split(new string[] {"#abc#"},StringSplitOptions.None)

Bobby 

No comments:

Post a Comment