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.

Download  Run Code

 
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.

Download  Run Code

 
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.

Download  Run Code

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.

Download  Run Code

That’s all about removing all null elements from a list in C#.