【问题标题】:SelectMany on tuples of { key, values } - obtain key in result?{键,值}元组上的SelectMany - 在结果中获得键?
【发布时间】:2016-02-25 21:46:52
【问题描述】:

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

我想使用 LINQ 并想到使用 SelectMany:

list.SelectMany(item => item.Values)

但是,如您所见,我失去了 Key 的转换。有什么诀窍?我想这应该很容易,我只是想见树木不见森林......

【问题讨论】:

  • 我猜你需要这样做:stackoverflow.com/questions/6428940/…
  • list.SelectMany(item => item.Values, (item, value) => Tuple.Create(item.Key, value))
  • 是的,森林...树木...过载...谢谢!
  • 后续问题:是否有可能为每个空值集合添加一个NULL 元组?
  • item.Values.DefaultIfEmpty()

标签: c# linq


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我也遇到了这种大脑冻结。从 cmets 中添加@PetSerAl 的答案:

    list.SelectMany(item => item.Values.DefaultIfEmpty(), (item, value) => Tuple.Create(item.Key, value))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-24
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      相关资源
      最近更新 更多