c# - 如何在 linq 中展平字典 <string,List<string>> 并将键保留在结果中

标签 c# linq dictionary flatten

你如何在linq中实现以下功能?我觉得应该有一个 Linq 替代品。

    var foods = new Dictionary<string, List<string>>();
    foods.Add("Cake", new List<string>() { "Sponge", "Gateux", "Tart" });
    foods.Add("Pie", new List<string>() { "Mud", "Apple" });
    foods.Add("Roll", new List<string>() { "Sausage" });

    var result = new List<Tuple<string, string>>();
    foreach (var food in foods)
    {
        foreach (var detail in food.Value)
        {
            result.Add(new Tuple<string, string>(food.Key, detail));
        }
    }

ie
cake <sponge, gateux>
pie <apple>

to

cake, sponge
cake, gateux
pie,  apple

谢谢

最佳答案

您可以使用 SelectMany扩展方法:

var result= foods.SelectMany(f=>f.Value.Select(s=>new Tuple<string, string>(f.Key, s)))
                 .ToList();

关于c# - 如何在 linq 中展平字典 <string,List<string>> 并将键保留在结果中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927634/

相关文章:

javascript - 交互式 map (非Flash)悬停问题

c# - 使用 C# 在 Open XML 电子表格中创建查询表

c# - 整数解析

c# - C# 中的 Mongodb $near 查询?

c# - 如何创建一个通用方法来遍历对象的字段并将其用作 Where 谓词?

c# - 为什么 Entity Framework 6 不支持 Discriminator 的显式过滤?

c# - Linq:选择分组列表

ios - 如何对存储在字典中的元组内的数组进行排序

python - 比较嵌套字典

c# - unity 2D - 如何通过在触摸屏上向上拖动手指来跳跃?