按基于键的字典分组
本文关键字:字典 于键 | 更新日期: 2023-09-27 18:33:33
我有一个Dictionary<string,string>
要分组。以下是一些示例键/值对
==========================
| Key | Value |
==========================
| A_FirstValue | 1 |
| A_SecondValue | 2 |
| B_FirstValue | 1 |
| B_SecondValue | 2 |
==========================
现在,我想根据字符的第一个实例之前的键中的第一个字母或单词对其进行分组'_'
所以,最终结果将是Dictionary<string, Dictionary<string, string>>
.对于上面的示例,结果将是:
A -> A_FirstValue, 1
A_SecondValue, 2
B -> B_FirstValue, 1
B_SecondValue, 2
这可能吗?有人可以帮助我吗?
谢谢。
好吧,你可以使用:
var dictionary = dictionary.GroupBy(pair => pair.Key.Substring(0, 1))
.ToDictionary(group => group.Key,
group => group.ToDictionary(pair => pair.Key,
pair => pair.Value));
组部分将为您提供一个IGrouping<string, KeyValuePair<string, string>>
,随后的ToDictionary
会将每组键/值对转换回字典。
编辑:请注意,这将始终使用第一个字母。对于更复杂的方法,我可能会编写一个单独的 ExtractFirstWord(string)
方法,并在 GroupBy
lambda 表达式中调用它。
yourDictionary
.GroupBy(g => g.Key.Substring(0, 1))
.ToDictionary(k => k.Key, v => v.ToDictionary(k1 => k1.Key, v1 => v1.Value));
这是我想到的。应该有一些错误处理以确保密钥中存在_
,但应该让你开始。
var source = new Dictionary<string, int>();
source.Add("A_FirstValue", 1);
source.Add("A_SecondValue", 2);
source.Add("B_FirstValue", 1);
source.Add("B_SecondValue", 3);
var dest = new Dictionary<string, Dictionary<string, int>>();
foreach (KeyValuePair<string, int> entry in source) {
string prefix = entry.Key.Split('_')[0];
if (!dest.ContainsKey(prefix)) {
dest.Add(prefix, new Dictionary<string, int>());
}
dest[prefix].Add(entry.Key, entry.Value);
}