Linq-按列表每周分组 [英] Linq - Group by week on the List

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

问题描述

我想按星期对我的数据进行分组:

I want to group by week my data like this:

var result = stats.GroupBy(i => SqlFunctions.DatePart("week", i.date))
            .Select(g => new ReportModel
            {
                clicks = g.Select(x => x.clicks).Sum(),
                impressions = g.Select(x => x.impressions).Sum(),
                ...
            });

但是我得到这个错误:

只能从LINQ到Entities调用此函数.

This function can only be invoked from LINQ to Entities.

有什么问题,我该如何解决?

What's the problem and how can I fixed it?

推荐答案

SqlFunctions.DatePart(以及其他此类函数)不能作为常规方法调用.它只能用作数据库查询的一部分(IQueryable).因此,您必须使用另一种方法,例如:

SqlFunctions.DatePart (and other such functions) cannot be called as a regular method. It can only be used as a part of database query (with IQueryable). So you have to use another approach, for example:

stats.GroupBy(i => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
    i.date, CalendarWeekRule.FirstDay, DayOfWeek.Monday));

请注意所使用的文化以及GetWeekOfYear的参数(什么算作一年的第一周,什么算作一周的第一天).

Pay attention to the culture used and also parameters of GetWeekOfYear (what counts as first week of year and what counts as first day of week).

这篇关于Linq-按列表每周分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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