How to remove all the null elements inside a generic list in one go?

pencilCake picture pencilCake · Jun 18, 2010 · Viewed 119.9k times · Source

Is there a default method defined in .Net for C# to remove all the elements within a list which 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 only contains parameters which are not null.

Answer

Lance picture Lance · Jun 18, 2010

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);