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

如何将List<Stuff>的内容平滑转换为List<Parameter>?

简洁实现List到List的转换

针对你的需求,推荐用LINQ的SelectMany方法实现,无需手动计数遍历,代码简洁且可读性强:

// 假设你已有源列表
List<Stuff> stuffList = new List<Stuff>
{
    new Stuff { ItemOne = "Spoon", ItemTwo = "Fork" },
    // 其他Stuff对象...
};

// 转换逻辑
List<Parameter> parameterList = stuffList
    .SelectMany(stuff => new[]
    {
        new Parameter { name = nameof(Stuff.ItemOne), val = stuff.ItemOne },
        new Parameter { name = nameof(Stuff.ItemTwo), val = stuff.ItemTwo }
    })
    .ToList();

说明:

  • SelectMany会将每个Stuff对象生成的两个Parameter实例,扁平合并成一个最终列表,完美匹配你的转换规则。
  • 使用nameof(Stuff.ItemOne)替代硬编码字符串"ItemOne",后续属性名修改时能自动同步,避免手动改字符串引发的错误。

如果后续Stuff类可能新增属性,也可以用反射实现通用转换(但固定属性场景下,上面的方法性能更优):

List<Parameter> parameterList = stuffList
    .SelectMany(stuff => typeof(Stuff).GetProperties()
        .Select(prop => new Parameter
        {
            name = prop.Name,
            val = prop.GetValue(stuff) as string
        }))
    .ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:09:55