Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://msdn.microsoft.com/en-us/library/bb291976.aspx" rel="nofollow">First()</a> will throw an exception if the collection is empty. Using <a href="http://msdn.microsoft.com/en-us/library/bb337697.aspx" rel="nofollow">Any()</a> in your <code>Where()</code> call should indeed solve the problem, but you would have to write something like:</p> <pre><code>data.Where(d =&gt; d.ObjectsA != null &amp;&amp; d.ObjectsA.Any() &amp;&amp; d.ObjectsA.First().ObjectsB != null &amp;&amp; d.ObjectsA.First().ObjectsB.Any() &amp;&amp; d.ObjectsA.First().ObjectsB.First().Nr == 1); </code></pre> <p>That's not very nice, because <code>First()</code> ends up being called several times on the same data. I'd suggest adding a body to your lambda expression and using intermediate variables with <a href="http://msdn.microsoft.com/en-us/library/bb340482.aspx" rel="nofollow">FirstOrDefault()</a>:</p> <pre><code>data.Where(d =&gt; { if (d.ObjectsA != null) { var firstA = d.ObjectsA.FirstOrDefault(); if (firstA != null &amp;&amp; firstA.ObjectsB != null) { var firstB = firstA.ObjectsB.FirstOrDefault(); if (firstB != null) { return (firstB.Nr == 1); } } } return false; }); </code></pre> <p><strong>EDIT:</strong> The second code fragment above apparently does not work with LINQ to NHibernate. If you can use query syntax and don't have to check if <code>ObjectsA</code> and <code>ObjectsB</code> are <code>null</code>, you can write:</p> <pre><code>from d in data let firstA = d.ObjectsA.FirstOrDefault() let firstB = (firstA != null ? firstA.ObjectsB.FirstOrDefault() : null) where (firstB != null &amp;&amp; firstB.Nr == 1) select d; </code></pre>
 

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