EN
C# / .NET - remove empty strings from List
0
points
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