从给定键的字符串中提取属性 [英] Extract properties from a string given a key

查看:56
本文介绍了从给定键的字符串中提取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串有一个小问题

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 :.

我试图将其解析为Jtoken,因此请查看它是否可以正确序列化,但事实并非如此.

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:);

然后使用

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

但是我似乎无法将字符串解析为Json.Linq.JToken

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?

推荐答案

如何

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

它当前不是有效的JSON.如果您可以将其存储为有效的JSON,则可以让JSON解析器为您解析它,这样可以更好地处理值中的逗号和冒号(冒号后的部分).

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).

如果您只想存储本地化的文本形式,建议使用.resx资源文件.

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

这篇关于从给定键的字符串中提取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆