Convertir matriz de enteros a cadena separada por comas


Es una pregunta simple; soy un novato en C#, ¿cómo puedo realizar lo siguiente

  • Quiero convertir una matriz de enteros a una cadena separada por comas.

Tengo

int[] arr = new int[5] {1,2,3,4,5};

Quiero convertirlo en una cadena

string => "1,2,3,4,5"
Author: MickyD, 2011-01-21

5 answers

var result = string.Join(",", arr);

Esto utiliza la siguiente sobrecarga de string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);
 424
Author: Danny Chen,
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
2013-05-31 18:34:36

. NET 4

string.Join(",", arr)

. NET anterior

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))
 109
Author: leppie,
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
2011-01-21 07:56:54
int[] arr = new int[5] {1,2,3,4,5};

Puedes usar Linq para ello

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);
 9
Author: Manish Nayak,
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
2016-05-28 07:14:38

Puede tener un par de métodos de extensión para hacer esta tarea más fácil:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

Así que ahora solo:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
 5
Author: nawfal,
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
2013-05-31 19:07:36

Use el método LINQ Aggregate para convertir una matriz de enteros en una cadena separada por comas

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

La salida será

1,2,3,4

Esta es una de las soluciones que puede usar si no tiene.net 4 instalado.

 3
Author: sushil pandey,
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
2013-08-18 15:01:59