In my code I have a List of ObjectA each of which has a list of ObjectB. I would like to get one list of all the ObjectBs in my list of ObjectAs.
If I have this objects:
public class ObjectA
{
public string Name {get; set;}
public List<ObjectB> Children {get; set;}
}
public class ObjectB
{
public string ChildName {get; set;}
}
And this code:
void Main()
{
var myList =
new List<ObjectA>{
new ObjectA{
Name = "ItemA 1",
Children = new List<ObjectB>{
new ObjectB{ChildName = "ItemB 1"},
new ObjectB{ChildName = "ItemB 2"}
}
},
new ObjectA{
Name = "ItemA 2",
Children = new List<ObjectB>{
new ObjectB{ChildName = "ItemB 3"},
new ObjectB{ChildName = "ItemB 4"}
}
}
};
// What code would I put here to concat all the ObjectBs?
}
I want to get a List<ObjectB>
with 4 ObjectB
items:
ItemB 1
ItemB 2
ItemB 3
ItemB 4
var allObjectB = myList.SelectMany(x=>x.Children).ToList();
You can just use SelectMany
:
var result = mylist.SelectMany(a => a.Children).ToList();
SelectMany allows you to pass in a function that returns an IEnumerable<T>
, and it itself then returns an IEnumerable<T>
(unlike Select, which would return IEnumerable<IEnumerable<T>>
.
The result contains all of those enumerables concatenated together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With