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

.NET 6中如何用LINQ按TenantId合并多组对象数组为指定结构

解决方案

补全目标类型定义

首先给你提到的结构补全类名(方便后续使用),完整代码如下:

public class TenantSettingsGroup
{
    public Guid TenantId { get; set; }
    public SettingsType[] AllSettings { get; set; }
}

public class SettingsType
{
    public OrganisationConfiguration Settings { get; set; }
    public string TypeName { get; set; }
}

LINQ实现合并分组

不需要单独提取TenantId再循环填充,直接通过LINQ链式调用就能完成合并与分组:

// 第一步:把所有数组合并,同时给每个元素标记对应的类型名称和TenantId
var allCombinedItems = type1.Select(w => new { w.TenantId, w.Settings, TypeName = "type1" })
    .Concat(type2.Select(w => new { w.TenantId, w.Settings, TypeName = "type2" }))
    .Concat(type3.Select(w => new { w.TenantId, w.Settings, TypeName = "type3" }))
    .Concat(type4.Select(w => new { w.TenantId, w.Settings, TypeName = "type4" }));

// 第二步:按TenantId分组,转换为目标结构
var result = allCombinedItems.GroupBy(item => item.TenantId)
    .Select(group => new TenantSettingsGroup
    {
        TenantId = group.Key,
        AllSettings = group.Select(item => new SettingsType
        {
            Settings = item.Settings,
            TypeName = item.TypeName
        }).ToArray()
    })
    .ToArray();

额外说明

  • 若数组可能为null,可以用type1?.Select(...) ?? Enumerable.Empty<...>()处理,避免空引用异常
  • 同一个TenantId在多个数组中的配置会自动被收集到AllSettings数组中,完全符合你给出的示例场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:00:25