I'm trying to write this simple Linq query without success. Here's the original SQL Query:
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
Which return result like:
Windows 131
Linux 7
iOS 51
This is my linq query:
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();
}
This return the following result:
Windows 1
Linux 1
iOS 1
Thanks for helping
Try something like this:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.