问题
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