假设我有:
Dictionary<string, List<string>> test = new()
{
{ "animal", ["cat", "dog"] },
{ "fruit", ["banana", "apple"] }
};
我可以使用:
test.SelectMany(x => x.Value);
获得:
["cat", "dog", "banana", "apple"]
但是有可能得到:
[("animal", "cat"), ("animal", "dog"), ("fruit", "banana"), ("fruit", "apple")]
使用 LINQ 点语法以简单、可读的方式?
使用
.SelectMany()
展平由键和每个值组合而成的元组列表中的值。
var result = test.SelectMany(x => x.Value.Select(y => (x.Key, y)))
.ToList();
您可以在
SelectMany
本身中使用 LINQ 将数组值映射到所需的结构。例如,对于值元组:
var valueTuples = test
.SelectMany(x => x.Value.Select(val => (x.Key, val)))
.ToList();
这会将数组中的每个值转换为“当前”键和值对,并展平生成的集合。