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>
⚠️ 注意事项
-
空 List:返回空字符串,不会报错
List
m = new List ();
string s = string.Join(",", m); // s = "" -
性能:
- 少量数据:直接
string.Join(",", m)最简单 - 超大集合 :推荐
Select(x=>x.ToString())版本,减少装箱开销
- 少量数据:直接
-
空元素:
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的数字)的示例?