Search code examples
entity-frameworklinqlinqpad

Return default value if Query is Empty


I'm creating a linq query in which I need to return minimum and maximum values of the years and prices of cars.

Linqpad:

 var result = (from c in Cars           
                 where c.IsShowed == true
                       c.CarCod == carCod                                  
                 group c by c.CarCod into cg
                 select new  {
                 MinPrice = cg.Min(cv => cv.Price) ,
                 MaxPrice = cg.Max(cv => cv.Price),
                 MinYear =  cg.Min(cv => cv.Year),
                 MaxYear =  cg.Max(cv => cv.Year)
                  })
                 .SingleOrDefault();

result.Dump();

How would I return a default value, example 0, for all properties MinPrice, MaxPrice, MinYear, MaxYear if the query is empty.


Solution

  • You should declare intermediate Result class for that:

     var result = (from c in Cars           
                   where c.IsShowed && c.CarCod == carCod                                  
                   group c by c.CarCod into cg
                   select new Result {
                       MinPrice = cg.Min(cv => cv.Price) ,
                       MaxPrice = cg.Max(cv => cv.Price),
                       MinYear =  cg.Min(cv => cv.Year),
                       MaxYear =  cg.Max(cv => cv.Year)
                   })
                   .SingleOrDefault() ?? new Result();