我有一个格式的字符串 “键 1=值 1;键 2=值 2;键 3=值 3;”
我需要将其转换为上述键值对的字典。
解决此问题的最佳方法是什么? 谢谢。
最佳答案
是这样的吗?
var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
当然,如果不满足假设,这将失败。例如,如果文本格式不正确,则可能会抛出 IndexOutOfRangeException
,如果存在重复键,则会抛出 ArgumentException
。这些场景中的每一个都需要不同的修改。如果可能存在冗余空白,您可能需要根据需要调用一些 string.Trim
。
关于c# - 在 C# 中将分隔字符串转换为字典<string,string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4141208/