Extract properties from a string given a key

狂风中的少年 提交于 2019-12-13 05:08:44

问题


I have a small issue with an string

da:,de:,en:Henkell Brut Vintage,fr:,nl:,sv:

I need to map this string to an dictionary, such that the key is what is before : and the value being after :.

I tried to parse it to a Jtoken, so see whether it would be serialized properly but it does not seem to be the case.

var name = Newtonsoft.Json.Linq.JToken.Parse(da:,de:,en:Henkell Brut Vintage,fr:,nl:,sv:);

And then extract the desired property using

name.Value<String>("en").ToString());

But i cant seem to parse the string to the Json.Linq.JToken

My other idea was to map it to a dictionary, but that seem to be a bit overkill for this tiny string.

Any simple solution, such that I can extract values for specified key?


回答1:


How about

var dict = input.Split(',').Select(s => s.Split(':')).ToDictionary(a => a[0], a => a[1]);

It isn't currently valid JSON. If you can store it as valid JSON, you can let a JSON parser parse it for you, which would better handle things like commas and colons in the values (the parts after the colons).

If you just want to store localised forms of text, I suggest using .resx resource files.




回答2:


Same as Georges without using Linq

        string initial = "da:,de:,en: Henkell Brut Vintage,fr:,nl:,sv:";
        string[] comaSplit = initial.Split(',');
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        foreach (string split in comaSplit) {
            string[] colonSplit = split.Split(':');
            dictionary.Add(colonSplit[0], colonSplit[1]);
        }


来源:https://stackoverflow.com/questions/51050911/extract-properties-from-a-string-given-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!