-3

I have a C# app. In this C# app, I have an object that I'll call order. Inside of order is a property called Departments. Inside of Departments is a property called Items. I want to put all Items across all of the Departments into a List. Is there a more elegant solution than this:

var items = new List<Item>();
foreach (var department in order.Departments)
{
    foreach (var item in department.Items)
    {
        items.Add(item);
    }
}

While the above "works". It just seems like I could write it in a more condensed way. Yet, I haven't been able to figure out how.

Thanks,

6
  • 2
    Is AddRange () good enough for you? Commented Nov 11, 2016 at 13:23
  • 2
    Is there a reason you chose to post this question instead of googling it first? Or can you modify your question to show evidence that you researched and couldn't find what you were looking for? Here's what I got when I copied your title into google: google.com/… Commented Nov 11, 2016 at 13:25
  • And, I'd like to point out that with a 1.6K rep, you should know how this works by now... Commented Nov 11, 2016 at 13:28
  • @rory.ap All rep earned with questions, not answers Commented Nov 11, 2016 at 13:29
  • @ManfredRadlwimmer -- even more reason he should know how to ask... Commented Nov 11, 2016 at 13:30

1 Answer 1

3

You can use SelectMany in Linq for this.

var result = order.Departments.SelectMany(x => x.Items).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.