第一个Dictionary类似于
Dictionary<String, String> ParentDict = new Dictionary<String, String>();
ParentDict.Add("A_1", "1");
ParentDict.Add("A_2", "2");
ParentDict.Add("B_1", "3");
ParentDict.Add("B_2", "4");
ParentDict.Add("C_1", "5");我需要将其转换为新的Dictionary<String, Dictionary<String,String>>
结果将包含
Key Value
Key Value
_________________________________________________
"A" "A_1" "1"
"A_2" "2"
"B" "B_1" "1"
"B_2" "2"
"C" "C_1" "1"现在我使用nested for loop来做这件事。
如何使用LNQ或LAMBDA Expression执行此操作
发布于 2010-10-23 22:22:56
var result = ParentDict.GroupBy(p => p.Key[0].ToString())
.ToDictionary(g => g.Key, g => g.ToDictionary(x => x.Key, x => x.Value));发布于 2010-10-23 22:16:18
尝试:
var result = from p in ParentDict
group p by p.Key[0] into g
select new { Key = g.Key, Value = g };这将为您提供一个{ Key,Value }列表,其中Key将是"A“、"B”、"C“等,而Value将是来自ParentDict的KeyValuePair的原始实例。
您可以在以下MSDN页面上找到更多LINQ示例查询:
发布于 2010-10-23 22:17:18
我怀疑这样做的原因是因为您需要能够查找特定关键字字母的所有条目。在这种情况下,Lookup通常是更好的匹配:
var letterLookup = ParentDict.ToLookup(kv=>kv.Key[0]);如下所示可用:
//letterLookup['A'] is an IEnumerable<KeyValuePair<string,string>>...
Console.WriteLine(string.Join(", ",
letterLookup['A'].Select(kv=>kv.ToString()).ToArray()
)); // [A_1, 1], [A_2, 2]
Console.WriteLine(new XElement("root",
letterLookup['B'].Select(kv=>new XElement(kv.Key,kv.Value))
));// <root><B_1>3</B_1><B_2>4</B_2></root>
Console.WriteLine(letterLookup['B'].Any()); //true
Console.WriteLine(letterLookup['Z'].Any()); //false与字典相比,查找的优点是它可以为任何给定的键包含多个值(与字典不同),并且如果缺少某个键,则它具有一致的API :然后返回空的enumerable,而包含enumerable的字典可能抛出KeyNotFoundException、返回null或返回空的enumerable,这一切都取决于您是如何创建它的。
https://stackoverflow.com/questions/4004348
复制相似问题