.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
相关产品推荐
相关产品推荐

