0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

would that then be a Dictionary<string, string> dic = itemname.Split(',').Select(s => s.Split(':')).ToDitctionary(x => x[0], x => x[1]) or what type is the dictionary?
Yes, it would be a Dictionary<string, string>
0

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]); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.