C# LINQ SelectMany with Default
<p>I am looking for an elegant solution to aggregate a child collection in a collection into one large collection. My issue is when certain child collections could be null.</p>

<p>EG:</p>

<pre class="lang-cs prettyprint-override"><code>var aggregatedChildCollection = parentCollection.SelectMany(x=&gt; x.ChildCollection);
</code></pre>

<p>This throws an exception should any of the child collection objects be null. Some alternatives are:</p>

<pre class="lang-cs prettyprint-override"><code>// option 1
var aggregatedChildCollection = parentCollection
    .Where(x=&gt;x.ChildCollection != null)
    .SelectMany(x =&gt; x.ChildCollection);

// option 2
var aggregatedChildCollection = parentCollection
    .SelectMany(x =&gt; x.ChildCollection ?? new TypeOfChildCollection[0]);
</code></pre>

<p>Both would work but I am doing a certain operation on quite a few child collections on the parent, and it is becoming a bit unweilding.</p>

<p>What I would like is to create an extension method that checks if the collection is null and if so does what option 2 does - adds an empty array. But my understanding of Func is not to a point where I know how to code this extension method. I do know that the syntax I would like is like this:</p>

<pre class="lang-cs prettyprint-override"><code>var aggregatedChildCollection = parentCollection.SelectManyIgnoringNull(x =&gt; x.ChildCollection);
</code></pre>

<p>Is there a simple extension method that would accomplish this?</p>