[英]How to count write the linq query when the grouped bY column is in one table and the items are in another table
我正在尝试编写此简单的Linq查询,但没有成功。 这是原始的SQL查询:
SELECT os.OSName, COUNT(d.DOperatingSystemId)
FROM [dbo].[Device_OperatingSystem] os
LEFT JOIN [dbo].[Device_DeviceDetails] d
ON os.OperatingSystemID = d.DOperatingSystemId
GROUP BY os.OSName
哪个返回结果像:
Windows 131
Linux 7
iOS 51
这是我的linq查询:
public List<KeyValue> GetNumberOFDevicesByOperatingSystem()
{
var numberOFDevicesByOperatingSystem = new List<KeyValue>();
var rawQuery = GetAll()
.GroupBy(
os => os.OSName,
os => os.Devices,
(key, g) => new { key, g });
foreach (var item in rawQuery)
{
numberOFDevicesByOperatingSystem.Add(new KeyValue
{
Key = item.key,
Value = item.g.Count().ToString()
});
}
return numberOFDevicesByOperatingSystem.ToList();
}
这将返回以下结果:
Windows 1
Linux 1
iOS 1
感谢您的帮助
尝试这样的事情:
var osDevicesList = (
from os in context.Device_OperatingSystem
let devicesWithOSCount = (
from d in context.Device_DeviceDetails
where d.DOperatingSystemId == os.OperatingSystemID
select d.Id
).Count()
group devicesWithOSCount by os.OSName into g
select new {
OS = g.Key,
value = g.First()
}
);
return (from d in Device_DeviceDetails
group d by d.DOperatingSystemId into dddg
join os in Device_OperatingSystem on dddg.Key equals os.OperatingSystemID
select new KeyValue { Key = os.OSName, Value = dddg.Count()}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.