Eliminar comas extra de la cadena después de usar la cadena.Unir para convertir matriz a cadena (C#)


Pregunta Rápida aquí. Estoy convirtiendo una matriz en una cadena usando Cadena.Unir. Un pequeño problema que tengo es que, en la matriz algunas posiciones de índice estarán en blanco. Un ejemplo está abajo:

array[1] = "Firstcolumn"
array[3] = "Thirdcolumn"

Usando String.Join ( " ,", array);, obtendré lo siguiente:

Firstcolumn,, Thirdcolumn

Tenga en cuenta el extra ,. ¿Cómo puedo eliminar las comas adicionales de la cadena, o idealmente no incluir índices en blanco cuando se utiliza Cadena.¿Unirme?

Author: Chris, 2010-10-07

9 answers

Prueba esto:):

var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));

Esto unirá solo las cadenas que no sean null o "".

 83
Author: Lasse Espeholt,
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 08:28:39

Una solución simple sería usar linq, filtrando los elementos vacíos antes de unirse.

// .net 3.5
string.Join(",", array.Where(item => !string.IsNullOrEmpty(item)).ToArray());

En. NET 4.0 también puede hacer uso de string.IsNullOrWhiteSpace si también desea filtrar los elementos que están en blanco o consisten solo en caracteres de espacio en blanco (tenga en cuenta que en. NET 4.0 no tiene que llamar a ToArray en este caso):

// .net 4.0
string.Join(",", array.Where(item => !string.IsNullOrWhiteSpace(item)));
 34
Author: bernhof,
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-10-07 16:30:51

Podría usar linq para eliminar los campos vacíos.

var joinedString = String.Join(",", array.Where(c => !string.IsNullOrEmpty(c));
 3
Author: Andy Rose,
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-10-07 12:58:50
String.Join(",", array.Where(w => !string.IsNullOrEmpty(w));
 1
Author: Julien Hoarau,
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-10-07 12:59:52

Método de extensión:

public static string ToStringWithoutExtraCommas(this object[] array)
{
    StringBuilder sb = new StringBuilder();
    foreach (object o in array)
    {

        if ((o is string && !string.IsNullOrEmpty((string)o)) || o != null)
            sb.Append(o.ToString()).Append(",");
    }

    sb.Remove(sb.Length - 1, 1);

    return sb.ToString();
}
 1
Author: Richard J. Ross III,
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-10-07 13:25:21

Solución de expresión regular:

yourString = new Regex(@"[,]{2,}").Replace(yourString, @",");
 1
Author: Even Mien,
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-10-07 13:26:29
string.Join(",", Array.FindAll(array, a => !String.IsNullOrEmpty(a)));

¿Qué tal este? Contras y pros en comparación con la solución LINQ? Al menos es más corto.

 0
Author: Denis,
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-08-24 12:50:33
string.Join(",", string.Join(",", array).Split({","}, StringSplitOptions.RemoveEmptyEntries));

V ( ' _ ' ) V

 0
Author: Sam,
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-12-05 20:52:07

Método de extensión simple

namespace System
{
    public static class Extenders
    {
        public static string Join(this string separator, bool removeNullsAndWhiteSpaces, params string[] args)
        {
            return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
        }
        public static string Join(this string separator, bool removeNullsAndWhiteSpaces, IEnumerable<string> args)
        {
            return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
        }
    }
}

Uso:

var str = ".".Join(true, "a", "b", "", "c");
//or 
var arr = new[] { "a", "b", "", "c" };
str = ".".Join(true, arr);
 0
Author: Adaptabi,
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-10-25 23:08:03