Languages
[Edit]
EN

C# / .NET - remove empty strings from List

0 points
Created by:
Zeeshan-Peel
850

In this article, we would like to show you how to remove empty strings from List in C#.

Quick solution:

List<string> myList = new List<string> { "A", " ", "     ", "\n", "", "B", "C" };

myList = myList.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();

// Output:
// ["A", "B", "C"]

 

Practical example

In this example, we use System.Linq methods to remove empty strings from myList.

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
    public static void Main()
    {
        List<string> myList = new List<string> { "A", " ", "     ", "\n", "", "B", "C" };

        myList = myList.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();

        foreach (string item in myList)
            Console.WriteLine(item);
    }
}

Output:

A
B
C

References

  1. Enumerable.Where Method (System.Linq) | Microsoft Docs
  2. String.IsNullOrWhiteSpace Method (System) | Microsoft Docs
  3. Enumerable.ToList Method (System.Linq) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join