【发布时间】:2016-02-25 21:46:52
【问题描述】:
我有一个 { string Key, IEnumerable<string> Values } 项目列表,并希望将其转换为 { string Key, string Value } 项目列表,以便新列表包含每个 Key 的 n 项目。
我想使用 LINQ 并想到使用 SelectMany:
list.SelectMany(item => item.Values)
但是,如您所见,我失去了 Key 的转换。有什么诀窍?我想这应该很容易,我只是想见树木不见森林......
【问题讨论】:
-
list.SelectMany(item => item.Values, (item, value) => Tuple.Create(item.Key, value)) -
是的,森林...树木...过载...谢谢!
-
后续问题:是否有可能为每个空值集合添加一个
NULL元组? -
item.Values.DefaultIfEmpty()