我需要字典中的键/值内容。我不需要的是它不允许重复的 key 。
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);
如何返回允许重复键的字典?
最佳答案
使用 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
)
);
关于c# - 允许使用 LINQ 查询中的 ToDictionary() 重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156181/