c# - LINQ-to-SQL - 在日期对象中按周分组

标签 c# linq linq-to-sql

我正在 LINQ-to-SQL 中编写一个查询,该查询中有一个日期列。我想按“周”对结果进行分组。我该如何在 LINQ-to-SQL 中执行此操作?

谢谢

最佳答案

假设公历,“第一天”周规则,并且一周的第一天是星期一。

第一天周规则:

Indicates that the first week of the year starts on the first day of the year and ends before the following designated first day of the week

int firstDayOfWeek = (int)DayOfWeek.Monday;
var q = 
    from u in TblUsers
    let date = u.CreateDate.Value
    let num = date.DayOfYear - 1
    let num2 = ((int)date.DayOfWeek) - (num % 7)
    let num3 = ((num2 - firstDayOfWeek) + 14) % 7
    let week = (((num + num3) / 7) + 1)
    group u by week into g
    select new 
    {
        Week = g.Key,
        Count = g.Count ()
    };

关于c# - LINQ-to-SQL - 在日期对象中按周分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7822659/

相关文章:

c# - C++ 和 C# 中的混合数组

c# - NHibernate 3.1 查询等于

c# - 内存优化的 OrderBy 和 Take?

c# - Linq-to-Sql SubmitChanges 不更新字段......为什么?

c# - LINQ to SQL 划分筛选器以获得更好的性能

c# - DropDownList 不调用 SelectedIndexChanged?

c# - Autofixture:控制创建的 string[] 类型元素的数量

c# - linqTOsql 在运行时返回 "specified cast not valid"异常

c# - 在 .Net (C#) 中构建 Google 产品提要?

entity-framework - Include/ThenInclude 与 EF Core 中的 where