Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Concat child lists in a list [duplicate]

Tags:

c#

linq

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

like image 688
M Kenyon II Avatar asked Oct 18 '16 14:10

M Kenyon II


2 Answers

var allObjectB = myList.SelectMany(x=>x.Children).ToList();
like image 59
Niyoko Avatar answered Sep 30 '22 16:09

Niyoko


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.

like image 30
juunas Avatar answered Sep 30 '22 16:09

juunas