我有下表,我已经和其他几个人一起加入......
+------------+--------------+------------+-------------------------+--------------+---------+
| Id | SubscriberId | CashAmount | DateTime | SubscriberId | Email |
+------------+--------------+------------+-------------------------+--------------+---------+
| 7 | 3 | 32.00 | 2014-05-06 16:19:00.000 | 3 | k@k.com |
| 67 | 3 | 32.00 | 2014-06-22 11:34:00.000 | 3 | k@k.com |
| 68 | 4 | 12.00 | 2014-04-22 15:34:00.000 | 4 | b@b.com |
| 69 | 4 | 32.00 | 2014-05-06 16:20:00.000 | 4 | b@b.com |
| 70 | 5 | 2.00 | 2014-05-22 11:34:00.000 | 5 | c@c.com |
| 71 | 6 | 32.00 | 2014-06-22 11:34:00.000 | 6 | b@b.com |
| 72 | 7 | 12.00 | 2014-05-22 11:34:00.000 | 7 | a@a.com |
| 73 | 4 | 12.00 | 2014-06-22 11:34:00.000 | 4 | b@b.com |
| 74 | 6 | 12.00 | 2014-04-22 15:34:00.000 | 6 | b@b.com |
| 75 | 4 | 32.00 | 2014-04-22 15:34:00.000 | 4 | b@b.com |
| 76 | 4 | 6.00 | 2014-04-22 15:34:00.000 | 4 | b@b.com |
+------------+--------------+------------+-------------------------+--------------+---------+
我需要使用.NET中的Linq将这些记录分组到独特的月份。此外,每个独特月份应该有一个唯一订阅者列表,该月份的总捐赠总和(因为一个用户可以在一个月内多次捐赠)。这更深入,我确定如何处理我对SQL或Linq的了解。为了记录,因为我使用linq,EntitySet中的DateTime对象具有Month和Year对象。非常感谢你的帮助!
答案 0 :(得分:0)
使用GroupBy<TSource, TKey, TResult>(IQueryable<TSource>, Expression<Func<TSource, TKey>>, Expression<Func<TKey, IEnumerable<TSource>, TResult>>)
运算符,如下所示:
var result = dbContext.Subscriptions.GroupBy(item => new {
Year = item.DateTime.Year,
Month = item.DateTime.Month,
SubscriberId = item.SubscriberId,
},
(key, items) => new {
Year = key.Year,
Month = key.Month,
SubscriberId = key.SubscriberId,
CashAmount = items.Sum(item => item.CashAmount)
});