Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ: How to get items from an inner list into one list?
    primarykey
    data
    text
    <p>Having the following classes (highly simplified):</p> <pre><code>public class Child { public string Label; public int CategoryNumber; public int StorageId; } public class Parent { public string Label; public List&lt;Child&gt; Children = new List&lt;Child&gt;(); } </code></pre> <p>And having the following data:</p> <pre><code>var parents = new List&lt;Parent&gt;(); 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); </code></pre> <p>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 ?</p> <p>I can do the following but it does not appear to be optimal:</p> <pre><code>var validParents = from p in parents where p.Children.Any (c =&gt; c.CategoryNumber==1) select p; var selectedChildren = validParents.Select(p =&gt; from c in p.Children where c.CategoryNumber == 2 select c); </code></pre> <p>Here's what I get for selectedChildren:</p> <ul> <li><code>IEnumerable&lt;IEnumerable&lt;Child&gt;&gt;</code> <ul> <li><code>IEnumerable&lt;Child&gt;</code> <ul> <li>C2 2 20</li> </ul></li> <li><code>IEnumerable&lt;Child&gt;</code> <ul> <li>C4 2 30</li> </ul></li> </ul></li> </ul> <p>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 ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload