c# - 允许使用 LINQ 查询中的 ToDictionary() 重复键

标签 c# .net linq dictionary duplicates

我需要字典中的键/值内容。我不需要的是它不允许重复的 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/

相关文章:

C# 以 List 作为参数插入到 SQL 表中

c# - Linq 除了只考虑一个属性

c# - 为 MemoryCache(或任何缓存)实现通用 Get<T>

c# - Cosmos DB Azure 表 API o数据身份验证 REST/C#?

.net - 为什么不继承构造函数?

c# - linq group by 投影到带有非参数构造函数的类

c# - Linq 选择昨天的日期

c# - 向没有窗口的进程发送 WM_CLOSE 消息

c# - HTTP 绑定(bind) Azure 函数中的自动反序列化是否考虑区域设置特定信息?

c# - 替换文本文件中的文本 c#