You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将指定SQL查询转换为对应的LINQ语句?

SQL转LINQ 按年月分组统计ProviderPosts数量

EF Core 数据库查询写法(可直接翻译为对应SQL执行)

// 写法1:直接按格式化字符串分组,和原SQL逻辑完全对齐
var queryResult = await dbContext.ProviderPosts
    .GroupBy(post => new
    {
        Year = post.CreatedDate.ToString("yyyy"),
        Month = post.CreatedDate.ToString("MM")
    })
    .Select(group => new
    {
        Count = group.Count(),
        Year = group.Key.Year,
        Month = group.Key.Month
    })
    .ToListAsync();

若部分EF Core版本无法识别ToString("yyyy")/ToString("MM")的翻译,可以使用更兼容的写法,先按日期的年、月数值分组再格式化,执行效率和最终结果完全一致:

// 写法2:兼容版本,适配所有EF Core版本
var queryResult = await dbContext.ProviderPosts
    .GroupBy(post => new
    {
        post.CreatedDate.Year,
        post.CreatedDate.Month
    })
    .Select(group => new
    {
        Count = group.Count(),
        Year = group.Key.Year.ToString(),
        Month = group.Key.Month.ToString("00") // 补前导零,和原SQL的MM格式对齐
    })
    .ToListAsync();

内存集合查询写法(针对已加载到内存的ProviderPosts列表)

var memoryResult = providerPostsList
    .GroupBy(post => new
    {
        Year = post.CreatedDate.ToString("yyyy"),
        Month = post.CreatedDate.ToString("MM")
    })
    .Select(group => new
    {
        Count = group.Count(),
        Year = group.Key.Year,
        Month = group.Key.Month
    })
    .ToList();

内容的提问来源于stack exchange,提问作者Lujain Alskran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:00:05