与linq分组计数

时间:2015-04-03 15:03:54

标签: c# sql-server linq

我有一个表格,其中包含我尝试在分析页面上使用的访问者浏览器信息。该表包含BrowserType,BrowserName和BrowserVersion。我已经使用本机sql构建了查询,但我正在努力将其转换为linq。

这是我的SQL查询:

SELECT COUNT(1) AS visit, s.BrowserType, s.BrowserName, s.BrowserVersion FROM Stats s GROUP BY s.BrowserType, s.BrowserName, s.BrowserVersion;

这给了我一个如下所示的结果集:

Query Results

stats表显然包含其他数据,例如日期和用户信息,但假设我已经查询了相关的行/对象,只需要从中获取计数信息。如果我这样做,我的select子句会出错:

var groupedResults = from r in results
                    group r by new { BrowserType = r.BrowserType, BrowserName = r.BrowserName, BrowserVersion = r.BrowserVersion } into g
                    select new
                    {
                        Name = g.BrowserName,
                        Version = g.BrowserVersion,
                        Count = g.Count()
                    });

3 个答案:

答案 0 :(得分:1)

您需要使用Key property of IGrouping界面。 使用链式语法就像这样:

var groupedResults = results
    .GroupBy(x => new { x.BrowserType, x.BrowserName, x.BrowserVersion})
    .Select(x => new {x.Key.BrowserType, x.Key.BrowserName, x.Key.BrowserVersion})
    .ToArray();

答案 1 :(得分:0)

使用我的客户表我这样做了。这是你在找什么?

var f = from c in Customer
                    .GroupBy(b=>new { b.Firstname,b.Lastname})
                    .Select(g => new { 
                             Metric = g.Key, 
                             Count = g.Count() 
                   })
        select c;

生成了T-SQL

SELECT COUNT(*) AS [Count], [t0].[firstname] AS [Firstname], [t0].[lastname] AS [Lastname]
FROM [customer] AS [t0]
GROUP BY [t0].[firstname], [t0].[lastname]

答案 2 :(得分:0)

var groupedResults = from r in results
                    group r by new { r.BrowserType, r.BrowserName,r.BrowserVersion } into g
                    select new
                    {
                        Type=g.Key.BrowserType,
                        Name = g.Key.BrowserName,
                        Version=g.Key.BrowserVersion,
                         Count=g.Count()

                    });

Hope it will help you