Remove all null elements from a List in C#
This post will discuss how to remove all null elements from a list in C#.
1. Using List<T>.RemoveAll() method
List’s RemoveAll() method in-place removes all elements from a list that matches with the specified condition. It can be used as follows to remove null elements from a list of strings.
|
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", null }; strings.RemoveAll(s => s == null); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
The List<T>.RemoveAll() method accepts the Predicate<T> delegate that sets the conditions for the elements to be removed. To remove null, empty, and white-space characters from a list, you can use the predefined delegate IsNullOrWhiteSpace. Alternatively, you can use IsNullOrEmpty to remove null and empty strings from the List.
|
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", null }; strings.RemoveAll(string.IsNullOrEmpty); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
It is worth noting that the List<T>.Remove() method removes the first occurrence of the specified element from the list, and returns true if the item is successfully removed; false otherwise. Although not recommended, you can repeatedly invoke it within a loop to remove all occurrences of an element.
|
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", null }; while (strings.Remove(null)) {}; Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
2. Using Enumerable.Where() method
With LINQ, you can use the Enumerable.Where() method to filter a list on a predicate. Note that this creates a new list, but preserves the original ordering of the elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "B", null, "C", null }; strings = strings.Where(x => x != null).ToList(); Console.WriteLine(String.Join(", ", strings)); // A, B, C } } |
That’s all about removing all null elements 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 :)