如果查询为空,则返回默认值

时间:2018-10-11 00:08:40

标签: entity-framework linq linqpad

我正在创建一个linq查询,在其中我需要返回汽车的年份和价格的最小值和最大值。

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();

如果查询为空,我如何为所有属性MinPrice,MaxPrice,MinYear,MaxYear返回默认值,例如0。

1 个答案:

答案 0 :(得分:3)

您应该为此声明中间Result类:

 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();