C# `string.Join` 处理 `List<int>`

C# string.Join 处理 List<int>

string.Join 不能直接把 List<int> 当作 IEnumerable<string>,但有两种常用写法:

方式1:配合 .Select() 转字符串(推荐)

复制代码
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> m = new List<int> { 1, 2, 3, 4, 5 };

        // 逗号分隔
        string result = string.Join(",", m.Select(x => x.ToString()));
        Console.WriteLine(result); // 输出:1,2,3,4,5

        // 无分隔直接拼接
        string result2 = string.Join("", m.Select(x => x.ToString()));
        Console.WriteLine(result2); // 输出:12345
    }
}

需要引用:using System.Linq;

方式2:.NET 4.0+ / .NET Core 及以上重载(不用Select)

string.Join(string, IEnumerable<object>),int会隐式装箱,内部自动调用ToString()

复制代码
List<int> m = new List<int> { 10, 20, 30 };
string result = string.Join("|", m); 
// 输出:10|20|30

✅ 原理:List<int> 是 IEnumerable<int>,可隐式转为 IEnumerable<object>

⚠️ 注意事项

  1. 空 List:返回空字符串,不会报错

    List m = new List();
    string s = string.Join(",", m); // s = ""

  2. 性能:

    • 少量数据:直接 string.Join(",", m) 最简单
    • 超大集合 :推荐 Select(x=>x.ToString()) 版本,减少装箱开销
  3. 空元素:int 不可能为 null,不用处理null

拓展:自定义数字格式化

复制代码
List<int> m = new List<int> { 1, 2, 3 };
string result = string.Join(",", m.Select(x => x.ToString("D3")));
// 输出:001,002,003

如果你用的是 .NET Framework 3.5 ,只能用 Select 写法,没有 IEnumerable<object> 这个重载。

要不要顺便写一个带条件过滤(只拼接大于0的数字)的示例?

相关推荐
凌镜icecraft1 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
the3clipse1 天前
Windows 11 26H2 AI 功能使用指南:回顾、单击以执行与实时字幕
人工智能·windows·copilot+ pc·recall 回顾·单击以执行·实时字幕翻译·windows studio
Jeff-Tsai1 天前
一个不用注册方法的 JSON-RPC 包,怎么决定哪些方法能被调用?
c#·.net·asp.net core·json-rpc
the3clipse1 天前
Windows 11 26H2 账户登录与 Windows Hello 指南:并行验证、增强登录安全与无密码设置
windows·无密码登录·windows hello·增强登录安全性ess·pin与密码区别·动态锁·win11 26h2
承渊政道1 天前
Toonflow AI短剧教程:Windows部署、批量生成与角色一致性
人工智能·windows·cpolar·ai短剧·toonflow
rockey6272 天前
AScript正式推出Template模板引擎
c#
沐言Agent2 天前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
投研帮2 天前
C#文档管理系统开发实战:技术选型、全文检索与并发控制
c#·.net·文档管理系统
2395730493 天前
在 Avalonia 12 上用纯 .NET 重写 Monaco 编辑器:TKCode.Arc CodeEditor / DiffEditor / LSP 深度架构与实战
c#·.net·lsp·avalonia·monaco·codeeditor·tkcode.arc
柳鲲鹏3 天前
编译Windows版本的zlib
windows