我有这个工作代码:
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/