一个delimted字符串转换为字典<字符串,字符串>在C#中 [英] Convert a delimted string to a dictionary<string,string> in C#

查看:129
本文介绍了一个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.

这篇关于一个delimted字符串转换为字典<字符串,字符串>在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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