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

C#如何动态合并多个对象的Moment、Value、State数组为聚合对象

实现方案

前置修正

先说明原定义里的两处可优化点:

  • C#中日期类型是DateTime(注意大小写,原拼写Datetime有误)
  • 结合JSON示例来看,Value属性实际为数组类型,原定义的object可修正为object[],后续也会给出保留object类型的兼容方案

步骤1:定义相关类

原始数据类

public class SourceData
{
    public DateTime[] Moment { get; set; }
    // 如果坚持保留object类型,可改回public object Value { get; set; }
    public object[] Value { get; set; }
    public int[] State { get; set; }
}

合并结果类

public class MergedData
{
    // 若使用Newtonsoft.Json,将JsonPropertyName替换为JsonProperty即可
    [System.Text.Json.Serialization.JsonPropertyName("ms")]
    public DateTime[] Ms { get; set; }
    
    [System.Text.Json.Serialization.JsonPropertyName("vs")]
    public object[] Vs { get; set; }
    
    [System.Text.Json.Serialization.JsonPropertyName("ss")]
    public int[] Ss { get; set; }
}

步骤2:实现动态合并逻辑

使用LINQ的SelectMany方法即可实现任意数量实例、任意长度属性数组的无限制合并:

using System.Linq;

public static MergedData MergeSourceData(IEnumerable<SourceData> sourceList)
{
    // 空集合兜底,可根据业务需求调整默认返回逻辑
    if (sourceList == null || !sourceList.Any())
    {
        return new MergedData
        {
            Ms = Array.Empty<DateTime>(),
            Vs = Array.Empty<object>(),
            Ss = Array.Empty<int>()
        };
    }

    return new MergedData
    {
        // SelectMany会自动把所有实例的数组合并为一个一维数组
        Ms = sourceList.SelectMany(x => x.Moment ?? Array.Empty<DateTime>()).ToArray(),
        Vs = sourceList.SelectMany(x => x.Value ?? Array.Empty<object>()).ToArray(),
        Ss = sourceList.SelectMany(x => x.State ?? Array.Empty<int>()).ToArray()
    };
}

如果你需要保留原始类的Value为object类型,替换Vs的合并逻辑即可兼容单个值、数组两种场景:

Vs = sourceList.SelectMany(x => 
{
    if (x.Value is IEnumerable<object> enumerable)
        return enumerable;
    return new[] { x.Value };
}).ToArray()

步骤3:验证效果

用你给出的两个实例测试:

// 构造测试数据
var data1 = new SourceData
{
    Moment = new[] { DateTime.Parse("2021-11-15T13:12:45.273Z") },
    Value = new object[] { 2.166 },
    State = new[] { 1 }
};
var data2 = new SourceData
{
    Moment = new[] { DateTime.Parse("2021-11-15T13:12:45.273Z") },
    Value = new object[] { 1.548 },
    State = new[] { 2 }
};
var sourceList = new List<SourceData> { data1, data2 };

// 执行合并
var merged = MergeSourceData(sourceList);

// 序列化为JSON验证结果
var json = System.Text.Json.JsonSerializer.Serialize(merged, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

输出结果完全符合你给出的预期JSON结构。


逻辑说明

  • 支持任意数量的SourceData实例输入,无数量限制
  • 支持单个实例内的Moment/Value/State属性包含多个元素,会自动全部合并到结果数组中
  • 内置空属性兜底逻辑,即使某个实例的属性为null也不会抛出空引用异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:15:04