Linq 获取带有列表的字典的键值对

问题描述 投票:0回答:1

假设我有:

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 点语法以简单、可读的方式?

c# linq
1个回答
0
投票

使用

.SelectMany()
展平元组列表中的值。

var result = test.SelectMany(x => x.Value.Select(y => (x.Key, y)))
    .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.