c# - 使用 LINQ 语法扫描嵌套字典

标签 c# linq dictionary

我有这个工作代码:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

public class Example {
    public static void Main(string[] args) {
        var files = new Dictionary<string, Dictionary<string, int>>()
                   { { "file1", new Dictionary<string, int>() { { "A", 1 } } } };
        foreach(var file in files) {
            File.WriteAllLines(file.Key + ".txt", file.Value.Select(
                    item => item.Key + item.Value.ToString("000")).ToArray());
        }
    }
}

但我想将 foreach 更改为 LINQ 语法。我已经尝试过的都不起作用。

最佳答案

这就是你想要的吗?

var files = new Dictionary<string, Dictionary<string, int>>() 
            { { "file1", new Dictionary<string, int>() { { "A", 1 } } } };
files.ForEach(kvp =>
    File.WriteAllLines(kvp.Key + ".txt", kvp.Value.Select(
            item => item.Key + item.Value.ToString("000")).ToArray()));

根据 Alexei 的评论,IEnumerable.ForEach 不是标准的扩展方法,因为它暗示了变异,这不是函数式编程的目的。您可以使用辅助方法添加它 like this one :

public static void ForEach<T>(
    this IEnumerable<T> source,
    Action<T> action)
{
    foreach (T element in source)
        action(element);
}    

此外,您的原始标题暗示字典的初始化语法很笨拙。要减少大量元素的键入/代码空间,您可以做的是构建一个匿名对象数组,然后构建 ToDictionary()。不幸的是,性能影响很小:

var files = new [] { new { key = "file1", 
                           value = new [] { new {key = "A", value = 1 } } } }
    .ToDictionary(
        _ => _.key, 
        _ => _.value.ToDictionary(x => x.key, x => x.value));

关于c# - 使用 LINQ 语法扫描嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847650/

相关文章:

c# - LINQ where子句疑惑

c# - Linq 查询首选项

python - 将字典元组转换为嵌套字典

c# - 将工具栏的元素从折叠状态更改为可见状态不会改变它们的可见性

c# - 反序列化为 namespace 已更改的类型

javascript - 如何在C#中使用toaster显示ajax返回的消息?

c# - 在字符串集合中搜索

c# - Linq to Sql - 具有多个连接的不同项目的查询列表

python - 如何避免两次写入 request.GET.get() 以打印它?

c++ - 添加到 std::map 的元素是否会自动初始化?