简体   繁体   中英

Convert List<int> to string and vice versa?

I've looked for hours and can't find an easy way to do this. I have a list of integers, and need to store it as a string so I can post it to an SQL server. Then I need to convert it back from a string to a list of integers later. What is the simplest way to do that?

"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 ) );

When converting to and from strings that are read by machines, not humans, it's important to avoid using ToString and Parse without using CultureInfo.InvariantCulture to ensure consistent formatting regardless of a user's culture and formatting settings.

FWIW, I have my own helper library that adds this useful extension method:

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 );
}

Which tidies things up somewhat:

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

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

String is the 2nd worst format you can have. Only binary is slightly worse. If you got an Int, keep it an int. Do not transform anything into a string unless you really need to (like sending it via XML, use IO). This does not seem like such a case.

The only reason I can think you want to turn them into strings to build a DB query. But do not build SQL Queries via string concatenation. You only get SQL Injections doing that. Use SQL Parameters. If you do, there is no need to convert them to string. Something between the SQL Classes and the DBMS will deal with getting it transferred reliably.

If for some reason the SQL is actually storing that Data as NVARCHARS: Replace that DB design. There is no reason to ever have a DB store a number as string. It has proper Number Field Types in anything this side of MS Access.

最简单的方法是每次创建一个新列表,并在迭代时投射每个项目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM