加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 允许使用来自LINQ查询的ToDictionary()重复键

发布时间:2020-12-16 01:41:38 所属栏目:百科 来源:网络整理
导读:我需要字典中的Key / Value内容.我不需要的是它不允许重复的密钥. Regex template = new Regex(@"{(?key.+?)}(?value[^{}]*)");IDictionarystring,string dictionary = template.Matches(MyString) .CastMatch() .ToDictionary(x = x.Groups["key"].Value,
我需要字典中的Key / Value内容.我不需要的是它不允许重复的密钥.

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}},{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
        )
    );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读