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

ASP.NET C#:实现通用的对象数组转字符串函数

通用对象列表转字符串的泛型实现方案

要实现可复用的对象列表转字符串功能,核心是利用泛型+属性选择器,让工具函数能适配任意类型的对象,并指定要提取的字符串属性。下面是具体实现:

通用工具函数实现

public static class Utility
{
    /// <summary>
    /// 将对象列表转换为分隔符拼接的字符串
    /// </summary>
    /// <typeparam name="T">列表中对象的类型</typeparam>
    /// <param name="items">待处理的对象列表</param>
    /// <param name="selector">从对象中提取字符串的逻辑</param>
    /// <param name="separator">拼接用的分隔符,默认是"-"</param>
    /// <param name="skipEmpty">是否跳过空字符串,默认开启</param>
    /// <returns>拼接后的字符串</returns>
    public static string ToDelimitedString<T>(IEnumerable<T> items, Func<T, string> selector, string separator = "-", bool skipEmpty = true)
    {
        // 按选择器提取字符串,过滤空值(可选)后拼接
        var validStrings = items.Select(selector)
                               .Where(s => !skipEmpty || !string.IsNullOrEmpty(s));
        return string.Join(separator, validStrings);
    }
}

参数说明

  • T:泛型参数,代表列表中对象的具体类型(比如你的A、B类)
  • items:接收IEnumerable<T>而非IList,兼容更多集合类型(List、数组、LINQ查询结果等)
  • selector:委托参数,传入x => x.Code或x => x.Mode这类逻辑,告诉函数从对象中提取哪个字段
  • separator:可选参数,默认用-拼接,可自定义为其他分隔符(比如/、,)
  • skipEmpty:可选参数,默认跳过空字符串,和你原LINQ逻辑保持一致

调用示例

在你的Main方法中,可以这样调用工具函数:

public static void Main()
{
    Root root = new Root();
    List<A> obj = new List<A>();
    obj.Add(new A() { Code = "WAY" });
    obj.Add(new A() { Code = "DOWN" });
    obj.Add(new A() { Code = "WE" });
    obj.Add(new A() { Code = "GO" });
    root.A = obj;

    // 处理A类型列表,和原LINQ结果一致
    string resultA = Utility.ToDelimitedString(root.A, x => x.Code);
    Console.WriteLine(resultA); // 输出:WAY-DOWN-WE-GO

    // 测试B类型列表
    var bList = new List<B>
    {
        new B { Mode = "FLY" },
        new B { Mode = "" }, // 空值会被过滤
        new B { Mode = "HIGH" }
    };
    string resultB = Utility.ToDelimitedString(bList, x => x.Mode);
    Console.WriteLine(resultB); // 输出:FLY-HIGH

    // 自定义分隔符示例
    string customSepResult = Utility.ToDelimitedString(root.A, x => x.Code, separator: "/");
    Console.WriteLine(customSepResult); // 输出:WAY/DOWN/WE/GO
}

原代码问题分析

你原来的Utility.ToArray方法存在两个核心问题:

  1. 使用IList<Object>作为参数,丢失了对象的具体类型信息,无法访问A的Code或B的Mode属性
  2. 没有实现属性提取和字符串拼接的逻辑,导致无法生成预期的结果

完整可运行代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Root
{
    public List<A> A { get; set; }
    public List<B> B { get; set; }
}

public class A
{
    public string Code { get; set; }
}

public class B
{
    public string Mode { get; set; }
}

public static class Utility
{
    public static string ToDelimitedString<T>(IEnumerable<T> items, Func<T, string> selector, string separator = "-", bool skipEmpty = true)
    {
        var validStrings = items.Select(selector)
                               .Where(s => !skipEmpty || !string.IsNullOrEmpty(s));
        return string.Join(separator, validStrings);
    }
}

public class HelloWorld
{
    public static void Main()
    {
        Root root = new Root();
        List<A> obj = new List<A>();
        obj.Add(new A() { Code = "WAY" });
        obj.Add(new A() { Code = "DOWN" });
        obj.Add(new A() { Code = "WE" });
        obj.Add(new A() { Code = "GO" });
        root.A = obj;

        // 原LINQ实现
        string originalResult = string.Join("-", root.A.Where(x => x.Code != "").Select(p => p.Code.ToString()).ToArray());
        Console.WriteLine(originalResult); // 输出:WAY-DOWN-WE-GO

        // 通用工具函数调用
        string utilityResult = Utility.ToDelimitedString(root.A, x => x.Code);
        Console.WriteLine(utilityResult); // 输出:WAY-DOWN-WE-GO
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:27:27