Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Select IList

Tags:

c#

linq

ilist

    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?

like image 296
Jason Marcell Avatar asked Mar 22 '26 08:03

Jason Marcell


2 Answers

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);
like image 167
Matt Hamilton Avatar answered Mar 23 '26 21:03

Matt Hamilton


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);
like image 39
JaredPar Avatar answered Mar 23 '26 22:03

JaredPar