C#LINQ的分组 [英] C# Linq Grouping

查看:153
本文介绍了C#LINQ的分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的LINQ实验时遇到了问题搞清楚分组。我通过几个教程,但由于某些原因不见了想不通这一点。

I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.

作为一个例子,说我有一个表(网站统计)与多个网站的ID是商店的计数多少访问者按类型总共有和过去30天里访问的每个网站。

As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.

╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║      1 ║           1 ║     10 ║  100 ║
║      1 ║           2 ║     40 ║  140 ║
║      2 ║           1 ║     20 ║  180 ║
╚════════╩═════════════╩════════╩══════╝

在SQL中,我可以很容易地得到SITEID 1计数与以下内容:

In SQL, I can easily get the counts for SiteID 1 with the following:

SELECT SiteId,  
       SUM(Last30) AS Last30Sum  
FROM Sites  
WHERE SiteId = 1  
GROUP BY SiteId

和应该得到的行状...

and should get a row like...

╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║      1 ║         50 ║
╚════════╩════════════╝

不过我不知道如何使用LINQ to得到这样的结果。我试过:

However I'm not sure how to get this result using Linq. I've tried:

var statsRecord = from ss in db.SiteStats  
    where ss.SiteId == siteId  
    group ss by ss.SiteId into ss  
    select ss;



但我不能回去总有类似 statsRecord .Last30

可有人请让我知道我要去哪里错了吗? 。任何帮助表示赞赏。

Can someone please let me know where I'm going wrong? Any help is appreciated.

推荐答案

实际上,虽然托马斯的代码将工作,更​​succint使用lambda表达式:

Actually, although Thomas' code will work, it is more succint to use a lambda expression:

var totals =
from s in sites
group s by s.SiteID into grouped
select new
{
    SiteID = grouped.Key,
    Last30Sum = grouped.Sum( s => s.Last30 )
};



,它使用而不需要嵌套LINQ操作求和扩展方法

which uses the Sum extension method without the need for a nested LINQ operation.

根据LINQ的101例 - 的http:// MSDN。 microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped

as per the LINQ 101 examples - http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped

这篇关于C#LINQ的分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆