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

如何用LINQ实现按实体、交易伙伴、服务、应用的嵌套分组?

问题描述

现有如下C#实体类结构(已支持一个实体对应多个服务与交易伙伴,且服务和交易伙伴各自可关联应用列表):

public Entity Entity { get; set; }

public Int64? ServiceId { get; set; }
public Service Service { get; set; }

public Int64 TradingPartnerId { get; set; }
public Entity TradingPartner { get; set; }

public List<Application.Application> FrontDoorApplications { get; set; }

需要实现按「实体→交易伙伴→服务→应用」的嵌套分组,最终输出结构示例如下:

Entity 1
    Trading Partner 1    
         Service A
            Application 1
            Application 2
         Service B    
Entity 1
     Trading Partner 2
         Service A
         Service B
实现方案

可以通过C# LINQ的多层分组来实现这个嵌套层级结构,假设你有一个包含上述实体类的集合(命名为entityRelations),具体实现代码如下:

分组逻辑

var groupedData = entityRelations
    // 第一层:按实体分组
    .GroupBy(er => er.Entity)
    .Select(entityGroup => new
    {
        Entity = entityGroup.Key,
        // 第二层:按交易伙伴分组
        TradingPartners = entityGroup
            .GroupBy(er => er.TradingPartner)
            .Select(tpGroup => new
            {
                TradingPartner = tpGroup.Key,
                // 第三层:按服务分组
                Services = tpGroup
                    .GroupBy(er => er.Service)
                    .Select(serviceGroup => new
                    {
                        Service = serviceGroup.Key,
                        // 合并当前服务下的所有应用,去重避免重复项
                        Applications = serviceGroup
                            .SelectMany(er => er.FrontDoorApplications)
                            .Distinct()
                            .ToList()
                    })
                    .ToList()
            })
            .ToList()
    })
    .ToList();

输出为示例格式

如果需要将分组后的数据输出成示例中的文本结构,可以遍历分组结果:

foreach (var entityItem in groupedData)
{
    // 输出实体名称,假设Entity类有Name属性
    Console.WriteLine(entityItem.Entity.Name);
    foreach (var tpItem in entityItem.TradingPartners)
    {
        Console.WriteLine($"    {tpItem.TradingPartner.Name}");
        foreach (var serviceItem in tpItem.Services)
        {
            Console.WriteLine($"         {serviceItem.Service.Name}");
            foreach (var app in serviceItem.Applications)
            {
                Console.WriteLine($"            {app.Name}");
            }
        }
    }
}

注意事项

  1. 确保Entity、Service、Application类正确实现了相等比较(或使用ID等唯一属性进行分组),否则GroupBy可能无法正确分组
  2. 如果数据中不会出现重复应用,可以去掉Distinct()提升性能
  3. 代码中的Name属性为示例,实际使用时替换为你项目中对应实体的展示字段即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:20:51