user70192 user70192 - 28 days ago 10
C# Question

C# - Joining All Lists of Lists together

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,

Answer

You can use SelectMany in Linq for this.

var result = order.Departments.SelectMany(x => x.Items).ToList();