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

LINQ实现:统计同一BusinessId对应的总浏览量

使用LINQ统计指定BusinessId的总浏览量

场景1:操作内存中的数据集合(如List)

假设对应数据库表的实体类定义如下:

public class BusinessViewRecord
{
    public int Id { get; set; }
    public int BusinessId { get; set; }
    public int ViewCount { get; set; }
    public DateTime RecordDate { get; set; }
    // 其他表字段...
}

要统计BusinessId为400的总浏览量,直接过滤目标数据后求和即可:

int targetBusinessId = 400;
List<BusinessViewRecord> dataRecords = GetYourDataSource(); // 替换为你的数据获取逻辑

int totalViews = dataRecords
    .Where(r => r.BusinessId == targetBusinessId)
    .Sum(r => r.ViewCount);

场景2:通过Entity Framework直接查询数据库

如果用EF框架对接数据库,写法类似,支持异步/同步两种调用方式:

int targetBusinessId = 400;

// 异步版本(Web/API场景推荐使用)
int totalViews = await _dbContext.BusinessViewRecords
    .Where(r => r.BusinessId == targetBusinessId)
    .SumAsync(r => r.ViewCount);

// 同步版本
// int totalViews = _dbContext.BusinessViewRecords
//     .Where(r => r.BusinessId == targetBusinessId)
//     .Sum(r => r.ViewCount);

拓展:统计所有BusinessId的总浏览量

如果需要一次性统计所有业务的总浏览量,用GroupBy分组后求和:

var allBusinessTotalViews = dataRecords
    .GroupBy(r => r.BusinessId)
    .Select(g => new {
        BusinessId = g.Key,
        TotalViews = g.Sum(r => r.ViewCount)
    })
    .ToList();

内容的提问来源于stack exchange,提问作者Pangomi IT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:45:37