Skip to content
TheChatArchiveThe Chat Archive
Amazon Novaamazon.nova-pro-v1:0· AmazonHugging Face LMArena Human Preference 140K

C#. Cómo puedo, utilizando LINQ, quitar de una List<string> los string vacios ?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514-thinking-32k’s answer.
  1. User

    C#. Cómo puedo, utilizando LINQ, quitar de una List los string vacios ?

  2. Amazon Nova Assistant

    Puedes usar LINQ para quitar los strings vacíos de una List utilizando el método Where. Aquí te muestro un ejemplo de cómo hacerlo:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            List<string> strings = new List<string> { "Hola", "", "mundo", "", "!", " " };
    
            // Usar LINQ para quitar los strings vacíos
            List<string> stringsSinVacios = strings.Where(s => !string.IsNullOrEmpty(s)).ToList();
    
            // Imprimir la lista resultante
            foreach (var str in stringsSinVacios)
            {
                Console.WriteLine(str);
            }
        }
    }
    

    Explicación:

    1. string.IsNullOrEmpty(s): Esta función verifica si un string es null o está vacío ("").
    2. .Where(s => !string.IsNullOrEmpty(s)): El método Where filtra los elementos de la lista según la condición especificada. En este caso, la condición es que el string no debe ser nulo ni vacío.
    3. .ToList(): Convierte el resultado del filtro de nuevo en una List<string>.

    Si también quieres quitar los strings que contienen sólo espacios en blanco, puedes usar string.IsNullOrWhiteSpace en lugar de string.IsNullOrEmpty:

    List<string> stringsSinVacios = strings.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
    

    Ejemplo Completo con IsNullOrWhiteSpace:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            List<string> strings = new List<string> { "Hola", "", "mundo", "   ", "!", " " };
    
            // Usar LINQ para quitar los strings vacíos y los que sólo contienen espacios en blanco
            List<string> stringsSinVacios = strings.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
    
            // Imprimir la lista resultante
            foreach (var str in stringsSinVacios)
            {
                Console.WriteLine(str);
            }
        }
    }
    

    En este caso, los strings "" y " " serán removidos de la lista.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.