Cómo unir int[] a una cadena separada por caracteres in.NET?


Tengo una matriz de enteros:

int[] number = new int[] { 2,3,6,7 };

¿Cuál es la forma más fácil de convertirlos en una sola cadena donde los números están separados por un carácter (como: "2,3,6,7")?

Estoy en C# y.NET 3.5.

Author: Mykola, 2008-09-28

10 answers

var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"

EDITAR :

Veo que varias soluciones anuncian el uso de StringBuilder. Alguien quejas que se Unen método debe tomar un argumentoumumerable.

Voy a decepcionarte:) Cadena.Join requiere array por una sola razón: rendimiento. El método Join necesita conocer el tamaño de los datos para preasignar efectivamente la cantidad necesaria de memoria.

Aquí está una parte de la implementación interna de String.Método de unión:

// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
    UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
    buffer.AppendString(value[startIndex]);
    for (int j = startIndex + 1; j <= num2; j++)
    {
        buffer.AppendString(separator);
        buffer.AppendString(value[j]);
    }
}

Soy demasiado perezoso para comparar realización de los métodos sugeridos. Pero algo me dice que Join ganará:)

 150
Author: aku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-20 07:01:46

Aunque el OP especificó. NET 3.5, las personas que quieran hacer esto en. NET 2.0 con C # 2 pueden hacer esto:

string.Join(",", Array.ConvertAll<int, String>(ints, Convert.ToString));

Encuentro que hay una serie de otros casos en los que el uso del Convert.funciones xxx es una alternativa más ordenada a una lambda, aunque en C#3 la lambda podría ayudar a la inferencia de tipo.

Una versión bastante compacta de C#3 que funciona con. NET 2.0 es esta:

string.Join(",", Array.ConvertAll(ints, item => item.ToString()))
 32
Author: Will Dean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-22 10:33:16

Una mezcla de los dos enfoques sería escribir un método de extensión en IEnumerable, que utiliza un StringBuilder. Aquí hay un ejemplo, con diferentes sobrecargas dependiendo de si desea especificar la transformación o simplemente confiar en toString simple. He nombrado el método " JoinStrings "en lugar de" Join " para evitar confusiones con el otro tipo de Join. Tal vez alguien puede llegar a un mejor nombre:)

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

public static class Extensions
{
    public static string JoinStrings<T>(this IEnumerable<T> source, 
                                        Func<T, string> projection, string separator)
    {
        StringBuilder builder = new StringBuilder();
        bool first = true;
        foreach (T element in source)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                builder.Append(separator);
            }
            builder.Append(projection(element));
        }
        return builder.ToString();
    }

    public static string JoinStrings<T>(this IEnumerable<T> source, string separator)
    {
        return JoinStrings(source, t => t.ToString(), separator);
    }
}

class Test
{

    public static void Main()
    {
        int[] x = {1, 2, 3, 4, 5, 10, 11};

        Console.WriteLine(x.JoinStrings(";"));
        Console.WriteLine(x.JoinStrings(i => i.ToString("X"), ","));
    }
}
 10
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-28 14:42:22
String.Join(";", number.Select(item => item.ToString()).ToArray());

Tenemos que convertir cada uno de los elementos a un String antes de poder unirlos, por lo que tiene sentido usar Select y una expresión lambda. Esto es equivalente a map en algunos otros idiomas. Luego tenemos que convertir la colección resultante de string de nuevo a un array, porque String.Join solo acepta un array de string.

El ToArray() es ligeramente feo creo. String.Join realmente debería aceptar IEnumerable<String>, no hay razón para restringirlo solo a los arrays. Esto es probablemente porque Join es de antes de los genéricos, cuando los arrays eran el único tipo de colección mecanografiada disponible.

 8
Author: JacquesB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-28 14:05:24

Si su matriz de enteros puede ser grande, obtendrá un mejor rendimiento utilizando un StringBuilder. Por ejemplo:

StringBuilder builder = new StringBuilder();
char separator = ',';
foreach(int value in integerArray)
{
    if (builder.Length > 0) builder.Append(separator);
    builder.Append(value);
}
string result = builder.ToString();

Editar: Cuando publiqué esto estaba bajo la impresión equivocada de que "StringBuilder.Append (int value) " gestionado internamente para anexar la representación de cadena del valor entero sin crear un objeto de cadena. Esto está mal: al inspeccionar el método con Reflector, se muestra que simplemente añade un valor.toString().

Por lo tanto, la única diferencia de rendimiento potencial es que esta técnica evita la creación de una matriz, y libera las cadenas para la recolección de basura un poco antes. En la práctica, esto no hará ninguna diferencia mensurable, por lo que he votado a favor esta mejor solución.

 5
Author: Joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:35

La pregunta es para "la forma más fácil de convertirlos en una sola cadena donde el número está separado por un carácter".

La forma más fácil es:

int[] numbers = new int[] { 2,3,6,7 };
string number_string = string.Join(",", numbers);
// do whatever you want with your exciting new number string

EDITAR: Esto solo funciona en.NET 4.0+, me perdí el requisito de. NET 3.5 la primera vez que leí la pregunta.

 5
Author: WebMasterP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 00:35:47

Estoy de acuerdo con la expresión lambda para legibilidad y mantenibilidad, pero no siempre será la mejor opción. La desventaja de usar los enfoques Stringumerable / toArray y StringBuilder es que tienen que hacer crecer dinámicamente una lista, ya sea de elementos o caracteres, ya que no saben cuánto espacio se necesitará para la cadena final.

Si el caso raro donde la velocidad es más importante que la concisión, lo siguiente es más eficiente.

int[] number = new int[] { 1, 2, 3, 4, 5 };
string[] strings = new string[number.Length];
for (int i = 0; i < number.Length; i++)
  strings[i] = number[i].ToString();
string result = string.Join(",", strings);
 2
Author: DocMax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-28 15:49:22
ints.Aggregate("", ( str, n ) => str +","+ n ).Substring(1);

También pensé que había una manera más simple. No sabes de performance, ¿alguien tiene alguna idea (teórica)?

 2
Author: void,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-08 16:15:12

En. NET 4.0, la combinación de cadenas tiene una sobrecarga para params object[], por lo que es tan simple como:

int[] ids = new int[] { 1, 2, 3 };
string.Join(",", ids);

Ejemplo

int[] ids = new int[] { 1, 2, 3 };
System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM some_table WHERE id_column IN (@bla)");
cmd.CommandText = cmd.CommandText.Replace("@bla",  string.Join(",", ids));

En.NET 2.0, es un poco más difícil, ya que no hay tal sobrecarga. Así que necesitas tu propio método genérico:

public static string JoinArray<T>(string separator, T[] inputTypeArray)
{
    string strRetValue = null;
    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();

    for (int i = 0; i < inputTypeArray.Length; ++i)
    {
        string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);

        if (!string.IsNullOrEmpty(str))
        { 
            // SQL-Escape
            // if (typeof(T) == typeof(string))
            //    str = str.Replace("'", "''");

            ls.Add(str);
        } // End if (!string.IsNullOrEmpty(str))

    } // Next i 

    strRetValue= string.Join(separator, ls.ToArray());
    ls.Clear();
    ls = null;

    return strRetValue;
}

En. NET 3.5, puede usar métodos de extensión:

public static class ArrayEx
{

    public static string JoinArray<T>(this T[] inputTypeArray, string separator)
    {
        string strRetValue = null;
        System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();

        for (int i = 0; i < inputTypeArray.Length; ++i)
        {
            string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);

            if (!string.IsNullOrEmpty(str))
            { 
                // SQL-Escape
                // if (typeof(T) == typeof(string))
                //    str = str.Replace("'", "''");

                ls.Add(str);
            } // End if (!string.IsNullOrEmpty(str))

        } // Next i 

        strRetValue= string.Join(separator, ls.ToArray());
        ls.Clear();
        ls = null;

        return strRetValue;
    }

}

Así que puede usar el método de extensión JoinArray.

int[] ids = new int[] { 1, 2, 3 };
string strIdList = ids.JoinArray(",");

También puede usar ese método de extensión en. NET 2.0, si agrega el ExtensionAttribute a su código:

// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}
 2
Author: Stefan Steiger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-17 10:25:59

Puedes hacer

ints.ToString(",")
ints.ToString("|")
ints.ToString(":")

Echa un vistazo

Separator Delimited toString for Array, List, Dictionary, Generic Genericumerable

 1
Author: Ray Lu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-22 10:18:32