我需要字典中的键/值内容。我不需要的是它不允许重复的密钥。
Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
IDictionary<string, string> dictionary = template.Matches(MyString)
.Cast<Match>()
.ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);
如何返回允许重复键的词典?
答案 0 :(得分:7)
使用Lookup类:
Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
ILookup<string, string> dictionary = template.Matches(MyString)
.Cast<Match>()
.ToLookup(x => x.Groups["key"].Value, x => x.Groups["value"].Value);
编辑:如果您希望获得“普通”结果集(例如{key1, value1}
,{key1, value2}
,{key2, value2}
而不是{key1, {value1, value2} }, {key2, {value2} }
)您可以获得IEnumerable<KeyValuePair<string, string>>
类型的结果:
Regex template = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");
ILookup<string, string> dictionary = template.Matches(MyString)
.Cast<Match>()
.Select(x =>
new KeyValuePair<string, string>(
x.Groups["key"].Value,
x.Groups["value"].Value
)
);