当分组的bY列在一个表中且项目在另一个表中时,如何计算写入linq查询

时间:2017-06-14 14:51:14

标签: c# linq

我正在尝试编写这个简单的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

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

@media hover:hover

答案 1 :(得分:1)

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();