Max return value if empty query

Naor picture Naor · Aug 6, 2011 · Viewed 63.5k times · Source

I have this query:

int maxShoeSize = Workers
    .Where(x => x.CompanyId == 8)
    .Max(x => x.ShoeSize);

What will be in maxShoeSize if company 8 has no workers at all?

UPDATE:
How can I change the query in order to get 0 and not an exception?

Answer

Ron K. picture Ron K. · Aug 6, 2011
int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                         .Select(x => x.ShoeSize)
                         .DefaultIfEmpty(0)
                         .Max();

The zero in DefaultIfEmpty is not necessary.