How to remove all null items inside a shared list at a time?

Is there a default method defined in .Net for C # to remove all items in a list that are null ?

 List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...}; 

Let's say some of the parameters are null ; I cannot know in advance, and I want to remove them from my list so that it contains only parameters that are not null.

+76
list null c # element
Jun 18 '10 at 12:57 on
source share
6 answers

You will probably need the following.

 List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...}; parameterList.RemoveAll(item => item == null); 
+155
Jun 18 '10 at 13:02
source share

I do not know any built-in method, but you can just use linq:

 parameterList = parameterList.Where(x => x != null).ToList(); 
+28
Jun 18 '10 at 13:02
source share

The RemoveAll method should do the trick:

 parameterList.RemoveAll(delegate (object o) { return o == null; }); 
+21
Jun 18 '10 at 13:02
source share
 List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...}; parameterList = parameterList.Where(param => param != null).ToList(); 
+3
Jun 18 '10 at 13:03
source share

The OfType() method will skip null values:

 List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...}; IList<EmailParameterClass> parameterList_notnull = parameterList.OfType<EmailParameterClass>(); 
+2
Oct 25 '15 at 9:41
source share

Easy and without LINQ:

 while (parameterList.Remove(null)) {}; 
+1
Jun 22 '16 at 12:45
source share



All Articles