-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,

TheRealVira
  • 1,444
  • 4
  • 16
  • 28
user70192
  • 13,786
  • 51
  • 160
  • 240

1 Answers1

3

You can use SelectMany in Linq for this.

var result = order.Departments.SelectMany(x => x.Items).ToList();
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
eocron
  • 6,885
  • 1
  • 21
  • 50