C# – LINQ: How to get items from an inner list into one list

clinqlist

Having the following classes (highly simplified):

public class Child
{
    public string Label;
    public int CategoryNumber;
    public int StorageId;
}

public class Parent
{
    public string Label;
    public List<Child> Children = new List<Child>();
}

And having the following data:

var parents = new List<Parent>();

var parent = new Parent() {Label="P1"};
parent.Children.Add(new Child() {Label="C1", CategoryNumber=1, StorageId=10});
parent.Children.Add(new Child() {Label="C2", CategoryNumber=2, StorageId=20});
parents.Add(parent);

parent = new Parent() {Label="P2"};
parent.Children.Add(new Child() {Label="C3", CategoryNumber=1, StorageId=10});
parent.Children.Add(new Child() {Label="C4", CategoryNumber=2, StorageId=30});
parents.Add(parent);

parent = new Parent() {Label="P3"};
parent.Children.Add(new Child() {Label="C5", CategoryNumber=3, StorageId=10});
parent.Children.Add(new Child() {Label="C6", CategoryNumber=2, StorageId=40});
parents.Add(parent);

Now, how would I get a list of children (with CategoryNumber=2) from the list of parents containing at least one child with CategoryNumber = 1 ?

I can do the following but it does not appear to be optimal:

var validParents = from p in parents
                   where p.Children.Any (c => c.CategoryNumber==1)
                   select p;
var selectedChildren = validParents.Select(p => from c in p.Children 
                                                where c.CategoryNumber == 2
                                                select c);

Here's what I get for selectedChildren:

  • IEnumerable<IEnumerable<Child>>
    • IEnumerable<Child>
      • C2 2 20
    • IEnumerable<Child>
      • C4 2 30

Is it possible to only have one flat list containing the two children elements instead of two sub-list? How would it translate in LINQ ?

Best Answer

You can string a couple queries together, using SelectMany and Where.

var selectedChildren = (from p in parents
                       where p.Children.Any (c => c.CategoryNumber==1)
                       select p)
                       .SelectMany(p => p.Children)
                       .Where(c => c.CategoryNumber == 2);

// or...

var selectedChildren = parents
                         .Where(p => p.Children.Any(c => c.CategoryNumber == 1))
                         .SelectMany(p => p.Children)
                         .Where(c => c.CategoryNumber == 2);