Count nulls in properties with one LINQ query
<p>Paste into LINQPad:</p>

<pre><code>void Main()
{
    List&lt;Data&gt; list = new List&lt;Data&gt;();
    list.Add(new Data());
    list.Add(new Data{a="a", b="b"});
    list.Add(new Data{a=null, b="b"});

    var queryA = from data in list where data.a == null select data;
    var queryB = from data in list where data.b == null select data;

    var countNulls = new {a = queryA.Count(),b = queryB.Count()};
    countNulls.Dump();
}

class Data
{
    public string a {get;set;}
    public string b {get;set;}
}
</code></pre>

<p>Instead of using queryA and queryB is it possible to do this in one query?</p>

<p><strong>Answer</strong>:<br>
All queries below generate exactly same SQL, so it's just a preference of coder what to choose.</p>

<pre><code>var countNulls = new 
    { 
        a = queryA.Count(), 
        b = queryB.Count() 
    };

    var countNulls2 = new 
    { 
        a = list.Count(d =&gt; d.a == null), 
        b = list.Count(d =&gt; d.b == null) 
    };

    var countNulls3 = list.Aggregate(
    new { a = 0, b = 0 },
    (acc, data) =&gt; new
    {
        a = acc.a + (data.a == null ? 1 : 0),
        b = acc.b + (data.b == null ? 1 : 0),
    });
</code></pre>

<p><strong>Update</strong>: apparently (thanks to Evan Stoev) this task can be done 20x faster on EF's DbSet and it creates one SQL query. </p>

<pre><code>var countNulls4 =
    (from data in db.Data
     group data by 1 into g
     select new
     {
         a = g.Sum(data =&gt; data.a == null ? 1 : 0),
         b = g.Sum(data =&gt; data.b == null ? 1 : 0)
     }).First();
</code></pre>