在LINQ中汇总多列

时间:2018-06-04 19:22:51

标签: c# linq

如何使用linq重现此查询?

SELECT 
SUM(SecondsSinceLastEvent) as AccessTime,
SUM (case when DownloadType = 0 then 1 end) FileDownloadCount,
SUM (case when DownloadType = 1 then 1 end) KortextDownloadCount,
SUM (case when Action = 'print' then 1 end) PrintCountFROM EReaderLogs WHERE PublishedContent_Id = XXX

1 个答案:

答案 0 :(得分:2)

在LINQ to Entities中,您需要先使用GroupBy才能使用多个聚合函数。要汇总列中的所有元素,您可以按某个静态键进行分组,这样一个组就可以是一个完整的表:

var query = context.EReaderLogs
    .Where(e => e.PublishedContent_Id == someValue)
    .GroupBy(a => 1, (k, g) => 
    {
        AccessTime = g.Sum(e => e.SecondsSinceLastEvent),
        FileDownloadCount = g.Sum(e => e.DownloadType == 0 ? 1 : 0),
        KortextDownloadCount = g.Sum(e => e.DownloadType == 1 ? 1 : 0),
        PrintCount = g.Sum(e => e.Action == "print" ? 1 : 0)
    });