Eri*_* J. 3 linq linq-to-objects
给定的
Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>()
{
"Apples", new List<string>() { "Green", "Red" },
"Grapefruits", new List<string>() { "Sweet", "Tart" },
}
Run Code Online (Sandbox Code Playgroud)
我希望创建一个从孩子到父母的映射,例如
“绿色”=>“苹果”
在我的特定用例中,子字符串将是全局唯一的(例如,无需担心 Green Grapefruits),因此映射可能是Dictionary<string,string>.
通过myDict传统的迭代来完成是相当简单的。
Dictionary<string, string> map = new Dictionary<string,string>();
foreach (KeyValuePair<string, List<string>> kvp in myDict)
{
foreach (string name in kvp.Value)
{
map.Add(name, kvp.Key);
}
}
Run Code Online (Sandbox Code Playgroud)
这可以用 Linq 完成吗?
关于只是展平相同的数据结构有一个非常相似的问题
但是,这不会保持与字典键的关系。
我在 SelectMany(相关问题中使用的方法)上查看了一个很好的可视化教程,但看不到与关键相关的方法。
听起来你想要:
var query = myDict.SelectMany(pair => pair.Value,
(pair, v) => new { Key = v, Value = pair.Key })
.ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)
请注意,SelectMany此处的第二个参数看起来有点奇怪,因为原始键成为最终字典中的值,反之亦然。
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |