【问题标题】:Lambda expression for nested foreach嵌套 foreach 的 Lambda 表达式
【发布时间】:2016-07-13 00:44:24
【问题描述】:

如何为以下嵌套的 foreach 循环编写 lambda 表达式:

var temp= new List<Items>();
foreach (var item in dto.Items)
{
    temp.Add(item);
    foreach (var child in item.Children)
    {
      temp.Add(child);
   }
}

【问题讨论】:

  • 想要顶级项目及其子项吗? “孙子”呢?顺序重要吗?
  • 我只想要顶级项目和他们的孩子。顺序无关紧要。

标签: c# linq foreach lambda


【解决方案1】:
dto.Items.SelectMany(item => item.Children).Concat(dto.Items);

应该这样做。

编辑:

正如 xanatos 所提到的,如果您想要与循环产生的顺序相同,则应该改用它:

dto.Items.SelectMany(item => new[] { item }.Concat(item.Children))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多