D J
D J

Reputation: 7028

query to Combine all childlist of all parent objects in one collection

I have a class structure like

public class Child
{
}

public class Parent
{
    public IEnumerable<Child> ListChild { get; set; }
}

and have a Test class

public class Test
{
    public IEnumerable<Parent> GetMethod()
    {
        List<Parent> collection = new List<Parent>();
        //// added multiple items of collection with childs.

        var allChildren = from c in collection
                              select c.ListChild;
        var childss = allChildren.Select((c) => c.Select((d)=>d));
        return childss;// wrong..and cant compile
    }
}

How to write a query to get all the childs in one IEnumerable collection without using foreach.

Thanks

Upvotes: 0

Views: 86

Answers (3)

user2614405
user2614405

Reputation:

Change the return type of GetMethod to IEnumerable<Child>

Upvotes: 0

Baldrick
Baldrick

Reputation: 11840

You need to use SelectMany, like this:

public IEnumerable<Child> GetMethod()
{
    List<Parent> collection = new List<Parent>();
    //// added multiple items of collection with childs.

    return collection.SelectMany(i => i.ListChild);
}

Upvotes: 4

pil0t
pil0t

Reputation: 2185

Try

collection.SelectMany(a => a.ListChild)

But it will be IEnumerable of Child not IEnumerable of Parent is it ok?

Upvotes: 4

Related Questions