Aporte:
string param = "1100,1110,0110,0001";Producción:
int[] matrix = new[] { 1,1,0,0, 1,1,1,0, 0,1,1,0, 0,0,0,1 };¿Lo que hice?
En primer lugar, dividí cadena a cadena [].
string[] resultantArray = param.Split(',');Creé un método, donde pasé mi cadena [].
var intArray = toIntArray(resultantArray); static private int[] toIntArray(string[] strArray) { int[] intArray = new int[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { intArray[i] = int.Parse(strArray[i]); } return intArray; }¿Tema?
Probé muchas soluciones de SO, pero ninguna me ayudó.
Terminó con una matriz sin ceros a la izquierda.
.Where(char.IsDigit)integer : char .Select(x => x-'0') (esto no es tan bonito como int.Parse o Convert.ToInt32 pero es súper rápido)Código:
string param = "1100,1110,0110,0001"; int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray(); Como comentó CodesInChaos, esto podría generar un error si hay otro tipo de dígitos dentro de su entrada como, por ejemplo, caracteres de dígitos tailandeses: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙' where char.IsDigit == true - si necesita manejar estos casos especiales, puede permitir solo 0 y 1 en su resultado .Where("01".Contains)
También puede eliminar las comas y convertir el resultado en caracteres de la siguiente manera usando Linq.
string param = "1100,1110,0110,0001"; int[] result = param.Replace(",", "").Select(c => (int)Char.GetNumericValue(c)).ToArray();otra forma más de hacer esto
static private IEnumerable<int> toIntArray(string[] strArray) { foreach (string str in strArray) { foreach (char c in str) { yield return (int)char.GetNumericValue(c); } } }