Remove empty strings from a List in C#
This post will discuss how to remove empty strings from a List in C#.
The List<T>.RemoveAll() method removes all the elements from a list that match the conditions defined by the specified predicate. The following code demonstrates the usage of List’s RemoveAll() method to in-place remove empty strings from a list and maintain the order of elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "", "B", "", "C", "" }; strings.RemoveAll(s => s == ""); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
To check whether the specified string is null or empty, use the String.IsNullOrEmpty() convenience method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "", "B", null, "C", "" }; strings.RemoveAll(s => string.IsNullOrEmpty(s)); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
To additionally check for the specified string consists of only white-space characters, use String.IsNullOrWhiteSpace() convenience method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "", "B", null, "C", "" }; strings.RemoveAll(s => string.IsNullOrWhiteSpace(s)); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
That’s all about removing empty strings from a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)