SelectMany 对 { key, value } 的元组 - 获取结果中的键?

D.R*_*.R. 6 c# linq

我有一个项目列表{ string Key, IEnumerable<string> Values },并希望将其转换为项目列表{ string Key, string Value },以便新列表包含n每个Key.

我想使用 LINQ 并且有使用的想法SelectMany

list.SelectMany(item => item.Values)
Run Code Online (Sandbox Code Playgroud)

然而,正如你所看到的,我失去了Key这种转变。有什么窍门呢?我想这应该很容易,我只是只见树木不见森林......

Ben*_*ull 5

我也遇到过这种大脑冻结的情况。从评论中添加@PetSerAl 的答案:

list.SelectMany(item => item.Values.DefaultIfEmpty(), (item, value) => Tuple.Create(item.Key, value))
Run Code Online (Sandbox Code Playgroud)


小智 -2

不是编译的代码,但这可能会回答您的问题

var finalList=list.SelectMany(item => item).Select(final => new{KeyName=item.Key,Coll=item.Values}).ToList();