1

how can I write lambda expression for the following nested foreach loops:

var temp= new List<Items>();
foreach (var item in dto.Items)
{
    temp.Add(item);
    foreach (var child in item.Children)
    {
      temp.Add(child);
   }
}
2
  • 3
    Do you only want the top level item and their children? What about the "grandchildren"? Does the order matter? Commented Mar 25, 2016 at 9:01
  • I just want top level item and their children. Order is not matter. Commented Mar 25, 2016 at 9:02

1 Answer 1

5
dto.Items.SelectMany(item => item.Children).Concat(dto.Items);

should do it.

Edit:

As xanatos mentioned, if you want to have the same order as your loops produce, you should use this instead:

dto.Items.SelectMany(item => new[] { item }.Concat(item.Children))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.