Dan*_*san 3 c# entity-framework-core .net-core
当列表中想要按属性进行分组并取特定属性的平均值或总和时,我遇到问题,我收到错误序列不包含元素。与我放置 DefaultIfEmpty 相比,我得到不同的错误NullReferenceException: 对象引用未设置到对象的实例。
代码是这样的:
var items = _repository.GetAllItems();
var groupedItems = items.GroupBy(x=> new {Year = x.DateCreate.Year, Month = x.DateCreate.Month})
.Select(s=> new ItemForListViewModel(){
Year = s.Key.Year,
Month = s.Key.Month,
AvgQnt = s.Where(x=>x.Price > 10).Average(x=>x.Qnt)
}).ToList();
Run Code Online (Sandbox Code Playgroud)
上面的代码给出错误序列不包含元素,而不是我更改
var groupedItems = items.GroupBy(x=> new {Year = x.DateCreate.Year, Month = x.DateCreate.Month})
.Select(s=> new ItemForListViewModel(){
Year = s.Key.Year,
Month = s.Key.Month,
AvgQntPrice10 = s.Where(x=>x.Price > 10).DefaultIfEmpty().Average(x=>x.Qnt),
AvgQntPrice100 = s.Where(x=>x.Price > 100).DefaultIfEmpty().Average(x=>x.Qnt
}).ToList();
Run Code Online (Sandbox Code Playgroud)
比我得到新的错误:NullReferenceException:对象引用未设置到对象的实例。
在数据库中,如果我运行查询,我会得到 AvgQntPrice10 的 0 和 AvgQntPrice100 的示例 15,什么是正确的。
问候,丹尼尔
问题当然是在调用的DefaultIfEmpty参数之后就可以了(CLR对于引用类型的默认值)。xAveragenull
回到最初的问题 -调用或空集合时,序列不包含元素异常。可以通过两种方式正确解决。MinMaxAverage
首先是,DefaultIfEmpty().Average(selector)使用不那么简洁但有效的组合来代替Select(selector).DefaultIfEmpty().Average(),例如
AvgQntPrice10 = s.Where(x => x.Price > 10).Select(x => x.Qnt).DefaultIfEmpty().Average(),
AvgQntPrice100 = s.Where(x => x.Price > 100).Select(x => x.Qnt).DefaultIfEmpty().Average()
Run Code Online (Sandbox Code Playgroud)
其次(也是我的首选)是利用 , 的可空重载这一事实Min,Max并且Average方法不会抛出空集合的序列不包含元素异常,而是返回null。因此,您所需要做的就是将选择器表达式类型转换为相应的可为空类型,并可以选择使用??聚合方法结果为该情况分配一个特殊值(例如0)。
例如,如果 the 的类型Qnt是int(如果不是,则使用正确的类型),则上面的内容可以写为
AvgQntPrice10 = s.Where(x => x.Price > 10).Average(x => (int?)x.Qnt) ?? 0,
AvgQntPrice100 = s.Where(x => x.Price > 100).Average(x => (int?)x.Qnt) ?? 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1368 次 |
| 最近记录: |