GroupBy基于键的字典

Lem*_*tor 4 c# group-by

我有一个Dictionary<string,string>我想要分组的.以下是一些示例键/值对

==========================
| Key            | Value |
==========================
| A_FirstValue   | 1     |
| A_SecondValue  | 2     |
| B_FirstValue   | 1     |
| B_SecondValue  | 2     |
==========================
Run Code Online (Sandbox Code Playgroud)

现在,我想根据字符的第一个实例之前的键中的第一个字母或单词对其进行分组 '_'

所以,最终结果将是Dictionary<string, Dictionary<string, string>>.对于上面的示例,结果将是:

A -> A_FirstValue, 1
     A_SecondValue, 2

B -> B_FirstValue, 1
     B_SecondValue, 2
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?有人可以帮我吗?

谢谢.

Jon*_*eet 9

好吧,你可以使用:

var dictionary = dictionary.GroupBy(pair => pair.Key.Substring(0, 1))
       .ToDictionary(group => group.Key,
                     group => group.ToDictionary(pair => pair.Key,
                                                 pair => pair.Value));
Run Code Online (Sandbox Code Playgroud)

组部分将为您提供一个IGrouping<string, KeyValuePair<string, string>>,然后ToDictionary将每组键/值对转换回字典.

编辑:请注意,这将始终使用第一个字母.对于任何更复杂的东西,我可能会编写一个单独的ExtractFirstWord(string)方法并在GroupBylambda表达式中调用它.

  • OP表示他希望"根据第一个字母'_''之前的第一个字母或单词对其进行分组,即使他的例子不支持:它总是一个字母.我认为`Key.Substring(0,p.Key.IndexOf('_')`将是一个更好的选择. (2认同)

Thi*_*tes 3

yourDictionary
    .GroupBy(g => g.Key.Substring(0, 1))
    .ToDictionary(k => k.Key, v => v.ToDictionary(k1 => k1.Key, v1 => v1.Value));
Run Code Online (Sandbox Code Playgroud)