c# - 将 List<int> 转换为字符串,反之亦然?

标签 c#

我已经找了几个小时,但找不到一个简单的方法来做到这一点。我有一个整数列表,需要将其存储为字符串,以便将其发布到 SQL 服务器。然后我需要稍后将它从字符串转换回整数列表。最简单的方法是什么?

最佳答案

"Use the force, Linq!" - Obi Enum Kenobi

using System.Linq;

List<Int32> numbers = new List<Int32>()
{
    1,
    2,
    3,
    4
};

String asString = String
    .Join(
        ", ",
        numbers.Select( n => n.ToString( CultureInfo.InvariantCulture ) )
    );

List<Int32> fromString = asString
    .Split( "," )
    .Select( c => Int32.Parse( c, CultureInfo.InvariantCulture ) );

当与机器而非人类读取的字符串相互转换时,避免使用 ToString 很重要和 Parse不使用CultureInfo.InvariantCulture确保格式一致,无论用户的文化和格式设置如何。

FWIW,我有自己的帮助程序库,它添加了这个有用的扩展方法:

public static String ToStringInvariant<T>( this T value )
    where T : IConvertible
{
    return value.ToString( c, CultureInfo.InvariantCulture );
}

public static String StringJoin( this IEnumerable<String> source, String separator )
{
    return String.Join( separator, source );
}

这会稍微整理一下:

String asString = numbers
    .Select( n => n.ToStringInvariant() )
    .StringJoin( ", " );

List<Int32> fromString = asString
    .Split( "," )
    .Select( c => Int32.Parse( c, CultureInfo.InvariantCulture ) );

关于c# - 将 List<int> 转换为字符串,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996210/

相关文章:

c# - 在 WPF 中制作 Gif 动画

c# - 从 C# 2.1 驱动程序正确关闭 MongoDB 数据库连接?

c# - 获取字符串中未使用的字符?

c# - 如何移动数组中的按钮并设置空的来源?

c# - 聚合与任意,用于扫描 IEnumerable<bool> 等对象

c# - 使用 Ninject 初始化具有初始值的字段

C#,实例化泛型类型 - 具有可变类型参数?

c# - 使用 AM/PM 将 6 位数字转换为时间

c# - 为什么在 C# 中经常看到 "null != variable"而不是 "variable != null"?

C# - 通用 CRUD 操作