Search code examples
.netvb.netlinqlinq-to-sql

Max or Default?


What is the best way to get the Max value from a LINQ query that may return no rows? If I just do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).Max

I get an error when the query returns no rows. I could do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter _
         Order By MyCounter Descending).FirstOrDefault

but that feels a little obtuse for such a simple request. Am I missing a better way to do it?


Solution

  • Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

    Dim x = (From y In context.MyTable _
             Where y.MyField = value _
             Select CType(y.MyCounter, Integer?)).Max
    

    Or in C#:

    var x = (from y in context.MyTable
             where y.MyField == value
             select (int?)y.MyCounter).Max();