将分隔的字符串转换为字典<string,string> </string,string>

时间:2014-02-04 04:34:12

标签: c# string dictionary delimiter

我有一个格式为

的字符串
=key1=value1=key2=value2=key3=value3

我需要将其转换为Dictionary<string,string>以获取上述键值对。 什么是最好的方法呢?

我试过这个:

var input = "key1=value1=key2=value2=key3=value3";
var dict = Regex.Matches(input , @"\s*(.*?)\s*=\s*(.*?)\s*(=|$)")
                .OfType<Match>()
                .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

2 个答案:

答案 0 :(得分:1)

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

var input = str.Split(new [] { '=' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<input.Length; i+=2)
{ 
    dict.Add(input[i], input[i+1]);
}

答案 1 :(得分:1)

这可以通过一点Linq来完成:

"=key1=value1=key2=value2=key3=value3"
    .Split('=')                            // Split into an array of strings
    .Skip(1)                               // Skip the first (empty) value
    .Select((v, i) => new { v, i })        // Get value and index
    .GroupBy(x => x.i / 2)                 // Group every pair together
    .ToDictionary(g => g.First().v,        // First item in group is the key
                  g => g.Last().v)         // Last item in group is the value