title: Razor skipping nested foreach loops
body: <p>In my database I have a string of child tables. In a razor view I am trying to loop through the ultimate parent and then filter a collection a few levels down.</p>
  
  <p>I have got it to work using the following extract:</p>
  
  <pre><code>@foreach (var artist in Model)
  {
      &lt;tr&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; artist.ArtistName)
          &lt;/td&gt;
      &lt;/tr&gt;
  
      foreach (var album in artist.Albums)
      {
          foreach (var song in album.Songs)
          {
              if (song.SongPlays != null)
              {
                  foreach (var songPlay in song.SongPlays)
                  {        
      &lt;tr&gt;
          &lt;td&gt;
               @Html.DisplayFor(a =&gt; songPlay.PlayTime)
          &lt;/td&gt;
      &lt;/tr&gt;
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>The issue with this is that I cannot sort the whole child collection by PlayTime. To solve this I then tried to get it working by skipping out the preceding foreach loops using:</p>
  
  <pre><code>    foreach (var songPlay in artist.Albums.SelectMany(a =&gt; a.Songs.SelectMany(b =&gt; b.SongPlays)))
      {
      &lt;tr&gt;
          &lt;td&gt;
              @Html.DisplayFor(a =&gt; songPlay.PlayTime)
          &lt;/td&gt;
      &lt;/tr&gt;
      }
  </code></pre>
  
  <p>This seems to work without the filter applied in the controller action, but returns a null result when the filter is applied. I have tried checking in the view if the result is null, but I could not  get this to work - something like:</p>
  
  <pre><code>if (artist.Albums.Select(a =&gt; a.Songs.Select(b =&gt; b.SongPlays)) != null)
      {
          foreach (var songPlay in artist.Albums.SelectMany(a =&gt; a.Songs.SelectMany(b =&gt; b.SongPlays)))
          { ...
  </code></pre>
  
  <p>I still get a null result, so I am presuming that the null check is not doing what I was hoping it would do.</p>
  
  <p>So if anyone can give me some guidance either on whether this approach is sensible and if I can do a null check on a grandchild collection somehow, or if there would be a better approach, it would be very much appreciated.</p>