c# - 为什么 LINQ Sum() 抛出“System.Collections.Generic.KeyNotFoundException”?
问题描述
在这里我有
System.Collections.Generic.KeyNotFoundException:“字典中不存在给定的键“EmptyProjectionMember”。
var res = (from c in _context.Check
join cp in _context.CheckProduct on c.Id equals cp.CheckId
join p in _context.Product on cp.ProductId equals p.Id
where c.Date.Date == date.Date
select (cp.Quantity * Decimal.ToDouble(p.Price))).Sum();
但是当我写这个时,代码正在工作:
var res = (from c in _context.Check
join cp in _context.CheckProduct on c.Id equals cp.CheckId
join p in _context.Product on cp.ProductId equals p.Id
where c.Date.Date == date.Date
select (cp.Quantity * Decimal.ToDouble(p.Price)));
double sum = 0;
foreach(var el in res)
{
sum += el;
}
为什么 Sum() 不起作用?
解决方案
尝试以下操作:
res = (from c in _context.Check
join cp in _context.CheckProduct on c.Id equals cp.CheckId
join p in _context.Product on cp.ProductId equals p.Id
where c.Date.Date == date.Date
select (cp.Quantity * Decimal.ToDouble(p.Price)))
.DefaultIfEmpty(0)
.Sum();
看起来没有什么可以选择的,所以在这种情况下,默认为 0。
在第二种情况下,您尝试迭代一个空的可枚举,因此它甚至不会进入 for each 子句。
推荐阅读
- python - 流文件内容作为程序输入
- php - 为什么我的 MySQL 检查插入数据是否存在的函数不起作用?
- apache-ranger - 有没有办法让 Ranger 策略执行 SHOW 数据库?
- c - 在 3 次握手期间向 ACK 数据包添加 TCP 选项
- java - 如何更新片段内的列表视图不在oncreateview方法中
- angular - Angular:如何配置日期选择器以禁用多个日期范围?
- electron - 我需要给我的电子图标填充吗?
- javascript - 如何将表格格式的数据用于节点中的电子邮件
- python - python日志记录模块中的log_level参数不会影响性能吗?
- flutter - 在 Flutter 中显示 Firestore 地图数据