簡體   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

我正在嘗試編寫此簡單的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM