将值的名称/描述拆分为 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/