Most elegant way to convert string array into a dictionary of strings

后端 未结 8 1039
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:39

Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?

8条回答
  •  没有蜡笔的小新
    2020-12-08 19:21

    The Question is not very clear, but Yes you can convert a string to Dictionary provided the string is delimited with some characters to support Dictionary pair

    So if a string is like a=first;b=second;c=third;d=fourth you can split it first based on ; then on = to create a Dictionary the below extension method does the same

    public static Dictionary ToDictionary(this string stringData, char propertyDelimiter = ';', char keyValueDelimiter = '=')
    {
        Dictionary keyValuePairs = new Dictionary();
        Array.ForEach(stringData.Split(propertyDelimiter), s =>
            {
                if(s != null && s.Length != 0)
                    keyValuePairs.Add(s.Split(keyValueDelimiter)[0], s.Split(keyValueDelimiter)[1]);
            });
    
        return keyValuePairs;
    }
    

    and can use it like

    var myDictionary = "a=first;b=second;c=third;d=fourth".ToDictionary();
    

    since the default parameter is ; & = for the extension method.

提交回复
热议问题