一个delimted字符串转换为字典<字符串,字符串>在C#中

问题描述:

我的格式为
的字符串键1 =值;键2 =值; KEY3 =值3;

I have a string of the format "key1=value1;key2=value2;key3=value3;"

我需要将其转换为字典上述键值对。

I need to convert it to a dictionary for the above mentioned key value pairs.

什么是去了解这一点的最好方法是什么?
感谢。

What would be the best way to go about this? Thanks.

这样呢?

var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
               .Select(part => part.Split('='))
               .ToDictionary(split => split[0], split => split[1]);



当然,这会如果假设不满足失败。例如,如果文本是不是在正确的格式和的ArgumentException 将被抛出一个 IndexOutOfRangeException 可能会被抛出如果有重复的键。每个场景需要不同的修改。如果多余的空白可能存在,你可能需要一些 string.Trim 呼吁是必要的。

Of course, this will fail if the assumptions aren't met. For example, an IndexOutOfRangeException could be thrown if the text isn't in the right format and an ArgumentException will be thrown if there are duplicate keys. Each of these scenarios will require different modifications. If redundant white-space could be present, you may need some string.Trim calls as necessary.