c# - 在 C# 中将包含项目和值的字符串拆分为字典

标签 c# string dictionary split

将值的名称/描述拆分为 dictionary <string, string> 的最佳方法是什么? ?

string test = postedByUser='Jason, Bourne' postedById='48775' Text='Some text in here' postedDate='2020-04-21'

所以理想情况下我想要

dictionary key = postedByUser, value = Jason, Bourne
dictionary key = postedById, value = 48775

等等

目前添加的代码

string test = @"postedByUser=Jason, Bourne' postedById='48775' Text='Some text in here' postedDate='2020-04-21'";

Dictionary<string, string> dict = new Dictionary<string, string>(); 

List<string> lst = test.Split('=').ToList(); 

foreach(string item in lst) 
{     
    // cant figure out how edit the orginal string to remove the item that has 
    //been split by the '=' 
}

最佳答案

好吧,下面的代码可以解决您的问题,但我建议您添加更多异常处理以使代码健壮。

string test = @"postedByUser='Jason, Bourne' postedById='48775' Text='Some text in here' postedDate='2020-04-21'";

Dictionary<string, string> dict = new Dictionary<string, string>();

List<string> keyvalues = test.Split("' ").ToList();
foreach(var keyvalue in keyvalues)
{
    var splitKeyValue = keyvalue.Split('=');
    dict.Add(splitKeyValue[0], splitKeyValue[1]);
}

编辑:

对于 .NET Framework 4.6,

List<string> keyvalues = test.Split(new string[] { "' " }, StringSplitOptions.None).ToList();

关于c# - 在 C# 中将包含项目和值的字符串拆分为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61362376/

相关文章:

c# - Azure 函数未由 EventHubTrigger 触发

c# - 标记为过时的接口(interface)方法在实现时不会从编译器发出消息

c# - 实现线程安全的队列或列表时,返回Count前是否需要加锁?

C 程序可以在命令行中运行,但不能在 Python 脚本中运行?

swift - 扩展 Dictionary,其中 Key 是 String 类型

swift - 如何根据键对字典进行排序并在 Swift 中对其各自的值进行排序

c# - YamlDotNet 找不到属性

javascript - 我需要比较两个字符串(或数组)并返回它们的相似度百分比,而不管它们的顺序如何

c++ - 如何使用 std::string 作为 stxxl::map 中的键

python - 重新排序 csv 中的列但字典损坏