Return 查询为空时的默认值
Return default value if Query is Empty
我正在创建一个 linq 查询,我需要在其中 return 年份和汽车价格的最小值和最大值。
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();
如果查询为空,我如何 return 所有属性 MinPrice、MaxPrice、MinYear、MaxYear 的默认值,例如 0。
你应该为此声明中间 Result
class:
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();
我正在创建一个 linq 查询,我需要在其中 return 年份和汽车价格的最小值和最大值。
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();
如果查询为空,我如何 return 所有属性 MinPrice、MaxPrice、MinYear、MaxYear 的默认值,例如 0。
你应该为此声明中间 Result
class:
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();