我有一个问题:
var resultb = unitOfWork.deviceInstanceRepository.Get()
.Select(s => new
{
DeviceId = s.DeviceId,
Name = s.Device.Name,
Manufacturer = s.Device.Manufacturer1.Name,
Quantity = s.Quantity
})
.GroupBy(w => new
{
w.DeviceId,
w.Name,
w.Manufacturer,
w.Quantity
}).ToList();
我想改变这一行:
Quantity= s.Quantity
进入
Quantity=Sum(s=>s.Quantity)
我找到了Click 但实现这一点仍然存在一些问题。 Intellisense中没有Sum方法。
当我更改Select
和GroupBy
的地点时
var resultb = unitOfWork.deviceInstanceRepository.Get()
.GroupBy(w => new
{
w.DeviceId,
w.Device.Name,
w.Device.Manufacturer,
w.Quantity
})
.Select(s => new
{
DeviceId = s.DeviceId,
Name = s.Device.Name,
Manufacturer = s.Device.Manufacturer1.Name,
Quantity = s.Sum(s=>s.Quantity)
})
我可以使用Sum
,但是像s.DeviceId
这样的行会引发Anonymous type does not contain definition of deviceId
错误。
s.Device.Name
和s>device.Manufacuter1.Name
答案 0 :(得分:5)
您必须在没有Quantity
属性的情况下进行分组,因为这是您要在分组中聚合的属性:
unitOfWork.deviceInstanceRepository.Get()
.GroupBy(w => new
{
DeviceId = w.DeviceId,
Device = w.Device.Name,
Manufacturer = w.Device.Manufacturer,
})
.Select(s => new
{
DeviceId = s.Key.DeviceId,
Name = s.Key.Device,
Manufacturer = s.Key.Manufacturer.Name,
Quantity = s.Sum(x => x.Quantity)
})