S G*_*S G 37 c# string dictionary delimiter
我有一个格式为"key1 = value1; key2 = value2; key3 = value3;"的字符串
我需要将其转换为上述键值对的字典.
最好的方法是什么?谢谢.
Ani*_*Ani 85
像这样的东西?
var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
Run Code Online (Sandbox Code Playgroud)
当然,如果不满足这些假设,这将失败.例如,IndexOutOfRangeException如果文本格式不正确,ArgumentException则可能抛出一个,如果有重复的键,则抛出一个.这些场景中的每一个都需要不同的修改.如果可能存在冗余空白区域,则可能需要进行一些string.Trim调用.
Biv*_*auc 18
更新了Ani,以考虑最后的半冒号.where子句将确保在创建和输入之前有一个键和值.
var dictionary = "key1=value1;key2=value2;key3=value3;"
.Split(';')
.Select (part => part.Split('='))
.Where (part => part.Length == 2)
.ToDictionary (sp => sp[0], sp => sp[1]);
Run Code Online (Sandbox Code Playgroud)
Kev*_*ker 11
看到令人敬畏的空白忽略,纠正具有或没有正则表达式的分号能力的最后值:
var dict = Regex.Matches("key1 = value1; key2 = value2 ; key3 = value3", @"\s*(.*?)\s*=\s*(.*?)\s*(;|$)")
.OfType<Match>()
.ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
Run Code Online (Sandbox Code Playgroud)
但严重的是,Ani值得.ToDictionary()的道具.我永远不会想到这一点.
小智 10
您可以使用JSON字符串执行此操作,例如:
var dic = JsonConvert.DeserializeObject<Dictionary<int, string>>("{'1':'One','2':'Two','3':'Three'}");
Run Code Online (Sandbox Code Playgroud)
你可以这样写它或循环它自己做.无论哪种方式.最终,你正在分裂;以获得项目对,然后开始=获取关键和价值.
string input = "key1=value1;key2=value2;key3=value3;";
Dictionary<string, string> dictionary =
input.TrimEnd(';').Split(';').ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]);
Run Code Online (Sandbox Code Playgroud)
循环版:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string[] items = input.TrimEnd(';').Split(';');
foreach (string item in items)
{
string[] keyValue = item.Split('=');
dictionary.Add(keyValue[0], keyValue[1]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53235 次 |
| 最近记录: |