我有以下代码:
decimal? sumFreightAmount = (db.Trips
.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
.Sum(p => p.FreightAmount));
if (sumFreightAmount.HasValue)
{
// my actions
}
else
{
sumFreightAmount = 0;
}
我可以通过以下方式编写:
decimal sumFreightAmount = (
db.Trips
.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
.Sum(p => p.FreightAmount) != null)
?
(db.Trips
.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
.Sum(p => p.FreightAmount)) : 0;
但是在这个地方我叫了两次linq扩展(并且记录很长)。我已经读过,我可以在最新版本的C#中编写更短的内容,比如
decimal sumFreightAmount = (db.Trips.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year).Sum(p => p.FreightAmount)?.0;
但找不到它。什么是最短的记录?
答案 0 :(得分:4)
最好的方法是使用GetValueOrDefault
decimal sumFreightAmount = db.Trips
.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
.Sum(p => p.FreightAmount)
.GetValueOrDefault();
编辑:正如@IvanStoev指出的那样,在这种情况下你也可以使用空合并运算符,它稍微短一些:
decimal sumFreightAmount = db.Trips
.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
.Sum(p => p.FreightAmount) ?? 0;