将字符串转换为Dictionary <string,byte>()</string,byte>

时间:2013-10-16 23:42:02

标签: c# dictionary

我有一个格式如下的字符串(字符串是一个连续的,没有新行返回)

 /CallDump/CallInfo/KVP[@Key='Group' and (@Value='Best Group')]:10,
 /CallDump/CallInfo/child::KVP[@Key='Dept' and (@Value='Customer Service' or @Value='Sales')]:240,
 compare(Recordings/Recording/Location, 'New York')=0:20,
 default:5,

我似乎无法找到将其转换为字典()

的非复杂方法

结果将是这样的:

键:/ CallDump / CallInfo / KVP [@ Key ='Group'和(@ Value ='Best Group')]价值:10

键:比较(录音/录音/位置,'纽约')= 0值:20

1 个答案:

答案 0 :(得分:4)

您可以使用Regex和LINQ:

轻松完成此操作
var input = @"/CallDump/CallInfo/KVP[@Key='Group' and (@Value='Best Group')]:10,
 /CallDump/CallInfo/child::KVP[@Key='Dept' and (@Value='Customer Service' or @Value='Sales')]:240,
 compare(Recordings/Recording/Location, 'New York')=0:20,
 default:5,";

var expression = new Regex(@"(.+):(\d{1,3})");

var result = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                  .Select(x => x.Trim())
                  .Select(x => expression.Match(x))
                  .Select(m => new { Key = m.Groups[1].Value, Value = byte.Parse(m.Groups[2].Value) })
                  .ToDictionary(x => x.Key, x => x.Value);

返回带有四个元素的Dictionary<string, byte>