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

C#使用LINQ按日期分组统计数据集中各分类条目数量的实现方法

你需要先根据数据结构定义对应实体,无关字段不需要在实体里声明,不会影响分组逻辑:

// 原始数据实体
public class OriginalEntry
{
    public string Timestamp { get; set; }
    public string Category { get; set; }
}

// 分类计数实体
public class FruitCount
{
    public string Category { get; set; }
    public int Count { get; set; }
}

// 最终结果实体
public class AggregatedEntry
{
    public string Timestamp { get; set; }
    public List<FruitCount> FruitCount { get; set; }
}

直接用两层GroupBy嵌套就能实现需求,示例代码如下,假设你原始数据集存在List<OriginalEntry> sourceEntries变量中:

var targetEntries = sourceEntries
    // 第一层按时间戳分组,拿到每个日期对应的所有数据
    .GroupBy(entry => entry.Timestamp)
    // 将每个日期组转换为目标结构
    .Select(dateGroup => new AggregatedEntry
    {
        Timestamp = dateGroup.Key,
        // 第二层按水果类别分组,统计每个类别的数量
        FruitCount = dateGroup
            .GroupBy(entry => entry.Category)
            .Select(cateGroup => new FruitCount
            {
                Category = cateGroup.Key,
                Count = cateGroup.Count()
            })
            .ToList()
    })
    .ToList();

如果只是临时使用不需要后续传递数据,也可以不用定义实体,直接用匿名类型生成结果:

var targetEntries = sourceEntries
    .GroupBy(e => e.Timestamp)
    .Select(g => new 
    {
        Timestamp = g.Key,
        FruitCount = g
            .GroupBy(e => e.Category)
            .Select(cg => new 
            {
                Category = cg.Key,
                Count = cg.Count()
            })
            .ToList()
    })
    .ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:12:04