Question

    List<MyParentClass> parents = new List<MyParentClass>();
    var parent1 = new MyParentClass("parent1");
    var parent2 = new MyParentClass("parent2");
    parents.Add(parent1);
    parents.Add(parent2);
    var child1 = new MyChildClass("child1");
    parent1.children.Add(child1);
    var child2 = new MyChildClass("child2");
    var child3 = new MyChildClass("child3");
    parent2.children.Add(child2);
    parent2.children.Add(child3);
    var foo = from p in parents
              select from c in p.children
                     select c;
    Assert.IsNotNull(foo);
    Assert.AreEqual(3, foo.Count());

NUnit.Framework.AssertionException: 
    expected: <3>
     but was: <2>

I think I'm getting an IList of ILists back, but I exepect just the three children. How do I get that?

Was it helpful?

Solution

I'm not overly confident with the query syntax, but I think this will flatten out the list of children:

var foo = from p in parents
          from c in p.children
          select c;

Using the extension-method syntax it looks like this:

var foo = parents.SelectMany(p => p.children);

OTHER TIPS

You are actually getting back an IEnumerable<IEnumerable<MyChildClass>>. In order to get a simple IEnumerable<MyChildClass> you can make the following call

var bar = foo.SelectMany(x => x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top