简体   繁体   English

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

[英]How to count write the linq query when the grouped bY column is in one table and the items are in another table

I'm trying to write this simple Linq query without success. 我正在尝试编写此简单的Linq查询,但没有成功。 Here's the original SQL Query: 这是原始的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

Which return result like: 哪个返回结果像:

Windows     131
Linux         7
iOS          51

This is my linq query: 这是我的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();
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM